making a class callable in same instance

泄露秘密 提交于 2020-08-22 08:09:15

问题


class Foo(object):
    def tick(self):
        print("something")

class Bar(object):
    def __init__(self):
        self.foo = Foo()

    def tick(self):
        #Here's what I do....
        self.foo.tick()

        #here's what my goal would be
        self.foo()

b = Bar()
b.tick()

That's essentially my goal. From what I've gathered I could change the tick function to __call__ and that would allow me to do what I wanted. A couple of the other answers said that this would make a new instance of the object, does that mean that it would use self.foo's memory? or would it make a whole new object, newly instanced? or make a copy of self.foo?

Also a couple of drawbacks to this which may or may not manifest themselves come to mind. For a particular part of my program, I check to see if the object has a __call__ to determine if the argument I'm passing is a function or a variable, and I don't really think I would want to allow that to be called (even though, I suppose the class technically would be a function at that point.) Is there any way to distinguish between a function and a callable class?

Is there anything else that would make doing this undesirable (and is it a pythonic way to work?)? My next thought had been that given that other variable prefixed with __ cant be used outside their class, but that doesnt seem to be the case here.


回答1:


Changing tick(self) to __call__(self) is the correct solution.

This has nothing to do with memory allocation. All __call__ signifies is the function which Python calls when you use (for an object foo) the syntax foo().

For your later question: to check whether something is an object, use isinstance or issubclass (possibly with the object class). And in my mind this answer is better than the accepted one for the "How do I determine if something is a function?" question you've probably seen.




回答2:


To make a class instance callable, all you need to do is implement a __call__ method. Then, to call the __call__ method, you just do: instance(arg1,arg2,...) -- in other words, you call the instance the same way you would call a function.

Note that you can alias __call__ with some other method defined on the class if you want:

>>> class Foo(object):
...     def tick(self):
...         print ("something")
...     __call__ = tick
... 
>>> a = Foo()
>>> a()
something
>>> a.tick()
something


来源:https://stackoverflow.com/questions/14585987/making-a-class-callable-in-same-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!