是否可以在连续运行时更改方法的行为?
例如,我们有以下两个类:
@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,那么第一次分配变量。即使使用A
:中foo
的默认值也能工作
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
不出所料!