AW: [Python-de] dynamisch Methoden aufrufen

Ulrich Berning ulrich.berning at t-online.de
Mit Nov 12 23:44:25 CET 2003


Ulrich Berning wrote:

> -------------------------------------
> class A:
>    def one(self, *args):
>        print "one called from a %s instance with:" % 
> self.__class__.__name__, args
>
>    def call_by_name(self, name, *args):
>        getattr(self, name)(*args) # Innerhalb der Klasse geht's mit self
>   class B(A):
>    def two(self, a, b, c):
>        print "two called from a %s instance with:" % 
> self.__class__.__name__, a, b, c
>   class C(B):
>    def three(self):
>        print "three called from a %s instance" % self.__class__.__name__
>       a = A()
> b = B()
> c = C()
>
> a.call_by_name("one", "Hello", "World")
>
> b.call_by_name("one")
> b.call_by_name("two", 1, 2, 3)
>
> c.call_by_name("one", [], None, {})
> c.call_by_name("two", 4, 5, 6)
> c.call_by_name("three")
>
> try:
>    c.call_by_name("four")
> except AttributeError, args:
>    print "Expected AtributeError:", args

Die Einrückung ist ein wenig durcheinander geraten, Sorry.
Ihr werdet's trotzdem verstehen :-)

Ciao, Ulli