访问包含类或对象的Python

发布于 2024-12-04 20:03:49 字数 405 浏览 1 评论 0原文

作为属性添加时如何访问当前类中的调用/外部/容器 python 类。考虑这个例子...

class a():
    @staticmethod
    def meth():
        print 'Who called me?'

class b():
    my_a = a

class c():
    my_a = a

b.my_a.meth()
>> Who called me?

c.my_a.meth()
>> Who called me?

所以这个例子中的问题是如何知道 a.meth() 中是否是从类 b 或类 a 调用的?

上面显然是静态类和方法,上面的解决方案是否也适用于包含对象?

How to access the calling/outer/container python class within current class when added as a property. Consider this example...

class a():
    @staticmethod
    def meth():
        print 'Who called me?'

class b():
    my_a = a

class c():
    my_a = a

b.my_a.meth()
>> Who called me?

c.my_a.meth()
>> Who called me?

So the question in this example is how to know within a.meth() whether it is being called from class b or class a?

The above are obviously static classes and methods, would the solution to the above also apply to containing objects?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

当爱已成负担 2024-12-11 20:03:49

没有好的方法可以知道 meth() 函数是如何访问的。当它被调用时,它只是一个函数。如果你使用@classmethod,你至少会得到传递给你的类,但在这种情况下,它们都是相同的a,所以我不确定你会得到你想要的。

您可能需要做更多的簿记才能获得您想要的信息。

There's no good way to know how the meth() function was accessed. By the time it is called, it is simply a function. If you use @classmethod instead, you will at least get the class passed to you, but in this case, they are both the same a, so I'm not sure you'll get what you want.

You will likely need to do some more bookkeeping to get the information you want.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文