除了将变量声明为新对象之外,还有什么方法可以将额外的信息应用于以后可以引用的 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)
关于python - 我如何提供可变的自定义元数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50339117/