使一个类在同一实例中可调用 [英] making a class callable in same instance

查看:75
本文介绍了使一个类在同一实例中可调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这基本上是我的目标。从我收集到的信息中,我可以将tick函数更改为 __ call __ ,这将使我能够做自己想做的事情。其他几个答案说这将创建该对象的新实例,是否意味着它将使用self.foo的内存?还是会形成一个全新的实例,新实例?还是制作self.foo的副本?

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?

还有一些缺点,这些缺点可能会或可能不会显现出来。对于程序的特定部分,我检查对象是否具有 __ call __ 以确定我要传递的参数是函数还是变量,而我没有我真的不认为我希望允许调用该函数(尽管从技术上讲,我认为该类在那时将是一个函数。)有没有办法区分函数和可调用类?

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?

是否还有其他事情会使此操作不受欢迎(这是Python的工作方式吗?)?我的下一个想法是,考虑到前缀为 __ 的其他变量不能在其类之外使用,但在这里似乎并非如此。

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.

推荐答案

勾号(self)更改为 __ call __(self)是正确的解决方案。

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

这与内存分配无关。所有 __ call __ 表示的是Python在使用(对于对象 foo )语法<$ c $时调用的函数。 c> foo()。

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().

对于后面的问题:要检查某物是否是对象,请使用 isinstance issubclass (可能带有 object 类)。在我看来,此答案比如何确定某物是否为函数?这个公认的答案要好。您可能已经看到的问题。

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.

这篇关于使一个类在同一实例中可调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆