What you want is a property. This is a special type of attribute that calls a custom getter function when getting the value, so you can make it dynamically return the correct plot.

class Data(object):
    def __init__(self, n):
        self.n = n

    @property
    def plot(self):
        return Plot(self.n)

    def __sub__(self, x):
        return Data(self.n - x)

As a side note, look at the data model to override python operators.

data = Data(10)
data -= 2
answer = data.plot.double()  # Calls the `plot()` function to get a value for `data.plot`.
print(answer)  # 16

Another way would be to link the Plot to the data, so when the data changes, the plot does to. A way to do it would be just to have it as an attribute, so when it changes, the attribute does too.

class Plot(object):
    def __init__(self, data):
        self.data = data

    @property
    def n(self):
        return self.data.n

    @n.setter
    def n(self, x):
        self.data.n = x

    def double(self):
        return self.n * 2

data = Data(10)
plot = Plot(data)
data.minus(2)
answer = plot.double()  # 16
Answer from Artyer on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › can somebody explain why i can change class variables with a self instance?
r/learnpython on Reddit: Can somebody explain why I can change class variables with a self instance?
November 3, 2022 -

I have this example code for a class:

tableclass.py

class ExampleClass(object):     
    def __init__(self):         
        self.EXAMPLE1 = self.set_example_1(False)         
        self.EXAMPLE2 = self.set_example_2()      

    def set_example_1(self, element):         
        if element:             
            return True 
        else:             
            False 
    
    def set_example_2(self):         
        if self.EXAMPLE1 == True:             
            return "YES" 
        else:             
            return "NO" 

Then I wrote a script to test the results of set_example_2:

# content of test_tableclass.py 
from tableclass import ExampleClass  

class TestExampleClass:     
    def test_set_example_2(self):        
        self.EXAMPLE1 = True 
        assert ExampleClass.set_example_2(self) == 'YES'         
        
        self.EXAMPLE1 = False 
        assert ExampleClass.set_example_2(self) == 'NO' 

After running: pytest test_tableclass.py I get the following output:

platform win32 -- Python 3.7.9, pytest-5.4.3, py-1.9.0, pluggy-0.13.1 
rootdir: C:\xxx\xxx\xxx\xxx\xxx 
plugins: mock-3.8.2 collected 1 item  

test_tableclass.py .                                                     [100%] 

I always thought that, in order to assign a certain self value you need to make a certain mock-class and then assign the value to that mock-class in example:

mock_class = mock.Mock() 
mock_class.EXAMPLE1 = True 
assert ExampleClass.set_example_2(self) == 'YES' 

Can somebody explain why the other method of assigning True to self.EXAMPLE1 also works in this case? Or where this is documented?

Top answer
1 of 3
1
So the short version that what you thought you had to do is better (even better if you can create that instance naturally), but what you did worked because python can be a lot more dynamic than it's a good idea to let it be. What you've discovered is that you can pass literally anything you want to SomeClass.some_method as the self argument. So long as what you pass has the attributes that the method requires, everything just works. So because you gave the attributes that your ExampleClass.set_example_2 method needs to your instance of your test class, it works. Your method looks for the attribute, sees it, gets it, and carries on. So it works. But in any more complex case, it could easily become very unwieldy and result in unpredictable code. "self" may have more attributes that interact differently than you expect in your method, or if you're not careful, preparing an attribute could accidentally overwrite an attribute that your test class actually needs, and weirdness happens. Modularity is broken. And what if you didn't explicitly set up some attribute that the class your testing needs in that method, but your test class had an attribute of that same name by coincidence? Well, the class your testing will use that attribute, leading to unpredictable and potentially hard to track down behavior. So sticking other things in for self can work, but it can really make code hard to understand and maintain, so you should avoid doing it when possible. When that's not possible and you do have to pass something else in as self, try to stick to well known patterns of creating something to put there rather than passing in a fraken object that's your test object modified to look like of sort of like what you want to test.
2 of 3
1
Nowhere in your above code are you doing anything with class variables, and your code as posted has several bugs and anti-patterns. Your code only sets instance variables, and only in the init method. Thus, you are not seeing what you think you are seeing happen. A class variable is declared in the class like this: class MyClass: instances = 1 def __init__(self): instances += 1 All instances of the MyClass class share the same class variable called "instances". When you increment it, all instances will see the same value. Anti-pattern 1 - function names should do what they say, but neither your "set_example_1" or "set_example_2" functions set anything. It's also not generally good form in Python to have setters and getters - just set the instance variables directly in the client code. Bug 1: "set_example_1" returns True if the passed parameter element is "truthy", but None if it's not. Just stating "False" on a line does not return False, it's a "redundant operation". You need to put return False for this to work as you expect. Anti-pattern 2: if self.EXAMPLE1 == True: this is a redundant comparison, as you are testing the truthiness of self.EXAMPLE1 against True. You shouldn't ever put == True or == False. The if statement already checks for the truthiness of its expression, so ust put if self.EXAMPLE1:.
Discussions

How do you code a self-updating class variable in python - Stack Overflow
25 Updating Class variable within a instance method · 0 Changing a variable's value inside a class in python More on stackoverflow.com
🌐 stackoverflow.com
python - update class variable using function defined within self - Stack Overflow
2 Class design: Initializing and updating instance variables elegantly · 1 How to call a self.value in a class function definition in python? More on stackoverflow.com
🌐 stackoverflow.com
July 31, 2018
How can I update a "self" variable in Python? - Stack Overflow
I'm having trouble understanding how to instantiate a class, and update that instances variables. If I __init__ a series of self.x variables, then instance that class, I want to update self.x = 40. More on stackoverflow.com
🌐 stackoverflow.com
python - Is there a way to update 'self' in a class when running the code? - Stack Overflow
Write a Python class (rotater) whose init function will take in a single additional argument which is a string; an internal variable (store) will be set to that string. There is also a function in this class called evolve which will take in a single additional argument n that specifies how many rotations should be applied to store. E.g., if store was "abed" and evolve(l) was called, then store would be updated ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Bobby Hadz
bobbyhadz.com › blog › python-update-class-variable
How to Update or access Class variables in Python | bobbyhadz
Class variables are shared by all instances and can be updated directly on the class or in a class method. ... Copied!class Employee(): # 👇️ class variable cls_id = 'employee' def __init__(self, name, salary): # 👇️ instance variables ...
🌐
YouTube
youtube.com › pythongpt
python class update self variables - YouTube
in python, classes are a fundamental concept in object-oriented programming (oop). they allow you to define blueprints for objects, which can contain data (a...
Published: September 25, 2023
Views: 74
🌐
Stack Overflow
stackoverflow.com › questions › 66725120 › how-do-you-code-a-self-updating-class-variable-in-python
How do you code a self-updating class variable in python - Stack Overflow
class CLASS: var_total = 0 def __init__(self, var): self.var = var CLASS.var_total+=var obj_one = CLASS(48) obj_two = CLASS(74) obj_three = CLASS(12) I don't want the var_total to be static, how do you code it to update automatically as the var property of the objects changes later in the code?
🌐
Python documentation
docs.python.org › 3 › tutorial › classes.html
9. Classes — Python 3.14.8 documentation
1 week ago - class Mapping: def __init__(self, iterable): self.items_list = [] self.__update(iterable) def update(self, iterable): for item in iterable: self.items_list.append(item) __update = update # private copy of original update() method class MappingSubclass(Mapping): def update(self, keys, values): # provides new signature for update() # but does not break __init__() for item in zip(keys, values): self.items_list.append(item) The above example would work even if MappingSubclass were to introduce a __update identifier since it is replaced with _Mapping__update in the Mapping class and _MappingSubclass__update in the MappingSubclass class respectively. Note that the mangling rules are designed mostly to avoid accidents; it still is possible to access or modify a variable that is considered private.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › g-fact-42-changing-class-members-python
Changing Class Members in Python | GeeksforGeeks
December 14, 2021 - # Program to show how to make changes to the # class variable in Python # Class for Computer Science Student class CSStudent: stream = 'cse' # Class Variable def __init__(self, name, roll): self.name = name self.roll = roll # New object for further implementation a = CSStudent("check", 3) print "a.stream =", a.stream # Correct way to change the value of class variable CSStudent.stream = "mec" print "\nClass variable changes to mec" # New object for further implementation b = CSStudent("carter", 4) print "\nValue of variable steam for each object" print "a.stream =", a.stream print "b.stream =", b.stream
🌐
Stack Overflow
stackoverflow.com › questions › 34054511 › python-classes-update-value-of-self
function - python classes update value of self - Stack Overflow
if y < len(s[0])-1: # Check right ... color) if y > 0: #Check left if s[x][y-1] == oldcolor: fill(s, x, y-1, color) self= fill(self, x, y, color) return self...
🌐
Quora
quora.com › How-do-you-make-a-global-variable-update-across-different-methods-in-Python
How to make a global variable update across different methods in Python - Quora
Answer (1 of 3): It’s discouraged to use global variables, unless you really need them. However, a common thing is to have a “global’ variable within a scope of a class. You can then share it across different methods… of the same class. [code]class Example(): def __init__(self): ...
🌐
Fylehq
stories.fylehq.com › fyle stories › demystifying class variables in python
Demystifying Class Variables In Python - by Kirti
December 2, 2022 - So, when we access the variable from the instance, Python checks if the variable exists in the instance’s dictionary-like object and if it does not exist then it checks the class’s dict-object. Now in case, we were directly updating the variable from the class, it works because the original variable in the class is updated.
🌐
Reddit
reddit.com › r/learnpython › what happens if i overwrite self ?
r/learnpython on Reddit: What happens if I overwrite self ?
January 13, 2024 -
Class School:
    def method_1(self,self2):
        self=self2

I guess I lose the self for that class. I guess I'm screwed and the method is then pointless as self would always be pointing to the class that called it?

I think what's more common is to either assign specific values to self (e.g. self.new_value=self2.value) or assign the whole self2 to self.self2 (e.g. self.self2 = self2)

🌐
Stack Overflow
stackoverflow.com › questions › 34835977 › python-class-how-to-update-variables
Python class - how to update variables - Stack Overflow
Copyi = 0 # always true, you just set i to 0 if i in range(0,101): # this is a no-op, equivalent to self.practical = self.practical + 0 self.practical += i # also a no-op self.theory += i · It doesn't make any sense with respect to your task or function signature. ... Sign up to request clarification or add additional context in comments. ... the code you sent makes sense to me but for some reason I'm still not getting the output i want. the variables aren't being updated and still are at 0.
🌐
PYnative
pynative.com › home › python › python object-oriented programming (oop) › python class variables
Python Class Variables With Examples – PYnative
September 8, 2023 - We should use the class variable carefully in Python because all objects share the exact copy. Thus, if one of the objects modifies the value of a class variable, then all objects start referring to the fresh copy. ... class Player: # class variables club = 'Chelsea' sport = 'Football' def __init__(self, name): # Instance variable self.name = name def show(self): print("Player :", 'Name:', self.name, 'Club:', self.club, 'Sports:', self.sport) p1 = Player('John') # wrong use of class variable p1.club = 'FC' p1.show() p2 = Player('Emma') p2.sport = 'Tennis' p2.show() # actual class variable value print('Club:', Player.club, 'Sport:', Player.sport)Code language: Python (python) Run