I want to know if it is possible to add an attribute to a variable in python. For example create the variable a=45 and then add as a label or property something like units=m/s
Thank you.
Since there is no such thing as a structure in python as in C, we could implement it by using either a class or a dictionary.
class method:
class Variables:
def __init__(self):
self.value = 25
self.unit = "m/s"
Dictionary method:
var1 = {'value': 25, 'unit': 'm/s'}
Since, it is an arbitrary data type you are wanting to implement, it'd be more helpful through classes. By doing that, you are free to do mathematical operations on the instances
The template would be:
class Speed(object):
def __init__(self, value, unit="m/s"):
self.magnitude = value
self.unit = unit
and you'd like to implement mathemtaical operation using methods in the class
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