在连续运行中更改方法行为

Change method behavior in consecutive runs

是否可以在连续运行时更改方法的行为?

比如我们有下面两个类:

@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()

我想要以下行为:

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

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

好的,我知道了。在setter中应该检查_x:如果是None,则变量是第一次赋值。即使使用默认值 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

我们有:

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

不出所料!