简体   繁体   English

Python追加功能作为点表示法

[英]Python append function as dot notation

def do_something(obj, func):
    obj.func()

My question is how do I call func on obj ? 我的问题是如何在obj上调用func func is a function of obj . funcobj的函数。 Is this even possible? 这有可能吗?

If func is an actual function of obj you can simply call it: 如果funcobj的实际功能,则可以简单地调用它:

func()

An example: 一个例子:

class Klass(object):
    def say_hi(self):
        print 'hi from', self

func = Klass().say_hi
func()   # hi from <__main__.Klass object at 0x024B4D70>

Otherwise if func is the name of the function (a string) then this will get it and call it: 否则,如果funcfunc的名称(字符串),则它将获取并调用它:

getattr(obj, func)()

Anyway func is a method defined on obj so you can directly call it using func() not by obj.func() as func itself is obj.func according to your question. 无论如何, func是在obj定义的方法,因此您可以直接使用func()而不是obj.func()来调用它,因为func本身是根据您的问题是obj.func

I have cleared this in the below 2 examples executed on Python interactive termainal . 我已经在下面两个在Python interactive termainal上执行的示例中清除了此Python interactive termainal

First I have defined a simple class then I have tried to access its instance method according to this question. 首先,我定义了一个简单的类,然后根据此问题尝试访问其实例方法。

>>> # Defining class
... 
>>> class MyClass(object):
...     def __init__(self):
...         self.name = "Rishikesh Agrawani"
...         self.age = 25
...     def doStuff(self):
...         print "DETAILS:\n"
...         print "NAME: %s" % (self.name)
...         print "AGE : %d" % (self.age)
... 
>>> # Instantiation
... 
>>> obj = MyClass()
>>> func = getattr(obj, "doStuff");
>>> func()
DETAILS:

NAME: Rishikesh Agrawani
AGE : 25
>>> 

Finally 最后

>>> 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
>>> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM