如何编写一个允许使用 __name__ 内省实例的类?
编写一个 Foo 类,允许其实例返回使用 __name__
创建的名称,
A = Foo(args)
str(A.__name__)
应该返回“A”
Writing a class Foo which allows its instances to return the names they were created with using __name__
,
A = Foo(args)
str(A.__name__)
should return 'A'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是不可能的(至少,并非在所有情况下,并且并非没有肮脏的伎俩)。在您的示例中,
A
是对Foo
类型的对象的引用。该对象不知道对其的引用是如何存储的。如果你这样写:那么
A
和B
都引用同一个对象,并且完全无法区分,因此你无法找到哪个对象用于保存对目的。当然,您可以扫描globals()
来查找对该对象的引用,然后您会找到A
和B
。但是,如果del A
,A
的所有痕迹都会消失。你想做什么?如果您解释了用例,也许我们可以建议您所要求的替代解决方案。
That's not possible (at least, not in all cases and not without dirty tricks). In your example,
A
is a reference to an object of typeFoo
. The object has no knowledge of how references to it are stored. If you write:then
A
andB
both reference the same object, and are totally indistinguishable, so you couldn't find which one was used to hold the first reference to the object. Of course, you could scanglobals()
for references to the object, and you would then findA
andB
. However, if youdel A
, all traces ofA
will have vanished.What are you trying to do? If you explained the use case, maybe we could suggest an alternative solution than what you asked.