Home > Software design >  Change method behavior in consecutive runs
Change method behavior in consecutive runs

Time:02-18

Is it possible to change the behavior of a method on consecutive runs?

For example, we have the following two classes:

@dataclass
class A():
    foo: str = None
    
    def print_message(self, first_time=True):
        if first_time:
            print("foo is set for the first time!")
        else:
            print("foo is re-assigned!")
    
class B(A):
    
    _x = None
    
    @property
    def foo(self) -> str:
        """ foo getter"""
        return _x

    @foo.setter
    def foo(self, value: str):
        """ foo setter"""
        self._x = value
        self.print_message()

I would like the following behavior:

my_B = B(foo = 'moo')
# "foo is set for the first time!" is printed

my_B.foo = 'koo'
# "foo is re-assigned!" is printed

CodePudding user response:

Ok, I've got it. The _x should be checked in the setter: if it is None, then the variable is assigned for the first time. Works even with the default value of foo in A:

from dataclasses import dataclass
@dataclass
class A():
    foo: str = 'moo'
    
    def print_message(self, first_time=True):
        if first_time:
            print("foo is set for the first time!")
        else:
            print("foo is re-assigned!")
    
class B(A):
    
    _x = None
    
    @property
    def foo(self) -> str:
        """ foo getter"""
        return _x

    @foo.setter
    def foo(self, value: str):
        """ foo setter"""
        if self._x is None:
            self.print_message()
        else:
            self.print_message(first_time=False)
        
        self._x = value

And we've got:

my_B = B()
# "foo is set for the first time!" is printed

my_B.foo = 'koo'
# "foo is re-assigned!" is printed

my_B.foo = 'soo'
# "foo is re-assigned!" is printed

As expected!

  • Related