Other than declaring the variable as a new object, is there a way I could apply extra information to a python variable that I could later refer back to?
someVar = ... # any variable type
someVar.timeCreated = "dd/mm/yy"
# or
someVar.highestValue = someValue
# then later
if someVar.timeCreated == x:
...
# or
if someVar == someVar.highestValue:
...
I see that this is essentially just an object, but is there a neat way I could do this without declaring an object separate to the python variable object itself?
Instances of user-defined classes (classes defined in Python source code) allow you to add whatever attributes you want (unless they have __slots__). Most built-in types such as str, int, list, dict, don't. But you can subclass them and then be able to add attributes, and everything else will behave normally.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With