我如何给变量自定义元数据?
How might I give a variable custom metadata?
除了将变量声明为新对象之外,还有什么方法可以将额外信息应用到 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 变量,以便我稍后可以引用?
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)