是否可以在連續運行中更改方法的行為?
例如,我們有以下兩個類:
@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
uj5u.com熱心網友回復:
好的,我明白了。應該在 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
正如預期的那樣!
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/428616.html
標籤:python-3.x 遗产 特性 蟒蛇数据类
上一篇:為什么Java記錄不支持繼承?
