Python append function as dot notation
1 2 | def do_something(obj, func): obj.func() |
我的问题是,我如何称呼
如果
1 | func() |
一个例子:
1 2 3 4 5 6 | class Klass(object): def say_hi(self): print 'hi from', self func = Klass().say_hi func() # hi from <__main__.Klass object at 0x024B4D70> |
否则,如果
1 | getattr(obj, func)() |
不管怎样,
我已经在下面两个在
首先,我定义了一个简单的类,然后我尝试根据这个问题访问它的实例方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | >>> # Defining class ... >>> class MyClass(object): ... def __init__(self): ... self.name ="Rishikesh Agrawani" ... self.age = 25 ... def doStuff(self): ... print"DETAILS: " ... print"NAME: %s" % (self.name) ... print"AGE : %d" % (self.age) ... >>> # Instantiation ... >>> obj = MyClass() >>> func = getattr(obj,"doStuff"); >>> func() DETAILS: NAME: Rishikesh Agrawani AGE : 25 >>> |
终于
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | >>> def do_something(obj, func): ... obj.func() ... >>> do_something(obj, func) Traceback (most recent call last): File"<stdin>", line 1, in <module> File"<stdin>", line 2, in do_something AttributeError: 'MyClass' object has no attribute 'func' >>> >>> def do_something(obj, func): ... print obj, func ... >>> do_something(obj, func) <__main__.MyClass object at 0x100686450> <bound method MyClass.doStuff of <__main__.MyClass object at 0x100686450>> >>> >>> >>> def do_something(obj, func): ... func() ... >>> do_something(obj, func) DETAILS: NAME: Rishikesh Agrawani AGE : 25 >>> |