我想在python中检索属性名来创建类似指针的东西,现在我使用以下语句,但我并不满意:
class foo:
name: str
last_name: str
class other:
def __init__(self, obj, var):
obj.__dict__[var] = "John"
f = foo("Jon", "Jon")
o = other(f, "name")
我想写作
o = other(f, f.name)
或者更好
o = other(f.name)
我尝试了一些函数来检索名称,但它只适用于对象,而不适用于对象的属性:
def retrieve_name(var: object) -> str:
for objname, oid in globals().items():
if oid is var:
return objname
if hasattr(oid, "__dict__"):
for child in oid.__dict__:
# dont work because id is the same if value is the same
if id(oid.__dict__[child]) == id(var):
return child
只有当我使用
retrieve_name(f) -> f
但如果我使用
retrieve_name(f.last_name) -> name
如果
f.name == f.last_name
因为
id(f.name) == id(f.last_name)
当字符串值相同时