Reg*_*ear 3 python metadata python-3.x
除了将变量声明为新对象之外,还有什么方法可以将更多信息应用于以后可以引用的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:
...
Run Code Online (Sandbox Code Playgroud)
我看到这本质上只是一个对象,但是有没有一种方法可以在不声明与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)
Run Code Online (Sandbox Code Playgroud)