访问包含类或对象的Python
作为属性添加时如何访问当前类中的调用/外部/容器 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有好的方法可以知道 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.