Home > Enterprise >  How to access updated class variable from within the class?
How to access updated class variable from within the class?

Time:10-10

Take this class:

class test:
    def __init__(self):
        self._a = "Thisa"
        self.b = "Thisb"
        self.ab = self.a   self.b

    @property
    def a(self):
        return self._a
    
    @a.setter
    def a(self, value):
        self._a = value

Test it from Thonny:

> from test import *

> boo = test()

> print(boo.a)
Thisa

> print(boo.b)
Thisb

> print(boo.ab)
ThisaThisb

> boo.a = "baa"

> print(boo.ab)
ThisaThisb

How do you get: "baaThisb" ?

CodePudding user response:

The a property doesn't do anything and is redundant. Just assign to a or b directly. ab should be the calculated property:

class Test:
    def __init__(self):
        self.a = 'Thisa'
        self.b = 'Thisb'

    @property
    def ab(self):
        return self.a   self.b

boo = Test()
print(f'{boo.a=}')
print(f'{boo.b=}')
print(f'{boo.ab=}')
boo.a = 'baa'
print(f'{boo.ab=}')
boo.b = 'blah'
print(f'{boo.ab=}')

Output:

boo.a='Thisa'
boo.b='Thisb'
boo.ab='ThisaThisb'
boo.ab='baaThisb'
boo.ab='baablah'

CodePudding user response:

Your problem is that self.ab is only being set in the constructor. You probably want something along these lines:

class test:
    def __init__(self):
        self._a = "Thisa"
        self._b = "Thisb"

    @property
    def a(self):
        return self._a

    @property
    def b(self):
        return self._b
    
    @a.setter
    def a(self, value):
        self._a = value

    @b.setter
    def b(self, value):
        self._b = value

    @property
    def ab(self):
        return self._a   self._b

CodePudding user response:

class Test: 
    def __init__(self): 
        self._a = "Thisa" 
        self.b = "Thisb" 

    @property
    def a(self):
        return self._a

    @property
    def ab(self):
        return self.a   self.b

    @a.setter
    def a(self, value):
        self._a = value

boo = Test()

print(boo.a) 
print(boo.b) 
print(boo.ab) 
boo.a = "baa"
print(boo.ab)
  • Related