Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python set attribute equal to another attribute

Tags:

python

Is it possible to have a class attribute targeting another attribute from the same object and have a function to update the value of the target?

class MyObject(object):
    def __init__(self):
        self.var_1 = 1
        self.var_2 = 2
        self.var_3 = 3
        self.current_var = self.var_1

    def update_var(self, value):
        self.current_var = ...

Expected outcome:

>>> x = MyObject()
>>> x.update_var(10)
>>> x.var_1
10
>>> x.current_var = x.var_2
>>> x.update_var(5)
>>> x.var_2
5
like image 466
bdoubleu Avatar asked Jun 18 '18 13:06

bdoubleu


People also ask

How do you assign a value to an attribute in Python?

Python setattr() Function Syntax var : object attribute which has to be assigned. val : value with which variable is to be assigned.

What is __ Getattr __ in Python?

__getattr__Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self).

What is __ slots __?

__slots__ solution From Python documentation: __slots__ allows us to explicitly declare data members (like properties) and deny the creation of __dict__ and __weakref__ (unless explicitly declared in __slots__ or available in a parent.)

How do you modify attributes in Python?

If you want your method to modify any attribute, you can pass its name as a string. You can then use getattr() and setattr() to get and set the attribute.


1 Answers

You can use the __dict__ of the object or as said by @bla setattr,
And Enum so you don't use string to specify the attribute:

from enum import Enum

class MyObject(object):
    def __init__(self):
        self.var_1 = 1
        self.var_2 = 2
        self.var_3 = 3
        self.current_var = None
    def update_var(self, value):
        if self.current_var is None:
            raise Exception('Current var is not set')
        self.__dict__[self.current_var.name] = value
        setattr(self, self.current_var.name, value) # Same result

m = MyObject()

attrs = vars(m)
attrs_enum = Enum("attrs_enum", attrs)


m.var_1 # 1
m.current_var = attrs_enum.var_1
m.update_var(10)
m.var_1 # 10

m.current_var = attrs_enum.var_2
m.var_2 # 2
m.update_var(20)
m.var_2 # 20

I don't like using a string to specify the attribute, but this is solution

like image 102
Yassine Faris Avatar answered Oct 13 '22 17:10

Yassine Faris