Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add an attribute to a variable in python?

Tags:

python

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.

like image 685
AJaramillo Avatar asked Dec 04 '25 12:12

AJaramillo


2 Answers

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'}
like image 154
T90 Avatar answered Dec 07 '25 01:12

T90


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

like image 24
nishparadox Avatar answered Dec 07 '25 01:12

nishparadox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!