我如何提供可变的自定义元数据?

问题描述 投票:2回答:1

除了将变量声明为新对象之外,有没有办法可以将额外的信息应用到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 python-3.x metadata
1个回答
4
投票

用户定义类(Python源代码中定义的类)的实例允许您添加所需的任何属性(除非它们具有__slots__)。大多数内置类型,如strintlistdict,都没有。但是你可以对它们进行子类化,然后能够添加属性,其他一切都会正常运行。

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)
© www.soinside.com 2019 - 2024. All rights reserved.