除了将变量声明为新对象之外,有没有办法可以将额外的信息应用到python变量中,以后我可以参考?
someVar = ... # any variable type
someVar.timeCreated = "dd/mm/yy"
# or
someVar.highestValue = someValue
# then later
if someVar.timeCreated == x:
...
# or
if someVar == someVar.highestValue:
...
我看到这基本上只是一个对象,但有一个简洁的方法,我可以做到这一点,而无需声明一个与python变量对象本身分开的对象?
用户定义类(Python源代码中定义的类)的实例允许您添加所需的任何属性(除非它们具有__slots__
)。大多数内置类型,如str
,int
,list
,dict
,都没有。但是你可以对它们进行子类化,然后能够添加属性,其他一切都会正常运行。
class AttributeInt(int):
pass
x = AttributeInt(3)
x.thing = 'hello'
print(x) # 3
print(x.thing) # hello
print(x + 2) # 5 (this is no longer an AttributeInt)