gpt4 book ai didi

python - 自省(introspection)以确定实例的原始绑定(bind)变量

转载 作者:行者123 更新时间:2023-11-30 23:33:42 28 4
gpt4 key购买 nike

是否有办法确定实例最初绑定(bind)到的变量?

使用函数我们可以做到这一点:

def f():
pass
print f.__name__
>> f
g = f
print g.__name__
>> f

我想要的是:

class c:
pass

mything = c()
print mything.__name__
>> mything

我想要这个的原因是为了为我正在编写的 API 提供更直观的日志记录/错误消息。如果有就太好了

print mything
>> instance of c originally bound to 'mything'

而不是通常的:

print mything
>> <__main__.c instance at 0x7fb7994b25a8>

并且(我认为?)不要让人们一直在 __init__ 中显式提供 __name__ 属性会很好......

这可能吗?可取吗?

最佳答案

你想要这样的东西(函数示例让我困惑):

class Foo(object):
# something here
pass

a = Foo()
b = Foo()
c = Foo()

print a.__name # a
print b.__name # b
print c.__name # c

?如果是这样,不,那是不可能的。该信息不能在实例内携带。许多实例可以指向同一个实例,如下所示:

>>> class Foo(object):
... pass
...
>>>
>>> a = Foo()
>>> b = a
>>> c = b
>>>
>>> print a
<__main__.Foo object at 0x01765B70>
>>> print b
<__main__.Foo object at 0x01765B70>
>>> print c
<__main__.Foo object at 0x01765B70>
>>>

它们都一样,要携带哪个实例名称,重点是什么?另一个问题在这里:

class Foo(object):
pass

a = [Foo(), Foo(), Foo()]

我能想到的唯一可能的解决方案是在初始化时标记实例:

>>> class Foo(object):
... def __init__(self, name):
... self.__name__ = name
...
>>> a = Foo('a')
>>> b = Foo('b')
>>> c = Foo('c')
>>>
>>> a.__name__
'a'
>>> b.__name__
'b'
>>> c.__name__
'c'
>>>

关于python - 自省(introspection)以确定实例的原始绑定(bind)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18602802/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com