有誰知道是否可以通過更改子類中的變數來更改父類的繼承變數?沒有在__init__孩子身上宣告它們?
class Foo(object):
def __init__(self):
self.data = "abc"
self.data_2 = self.data
class Bar(Foo):
def __init__(self):
super(Bar, self).__init__()
self.data = "def"
f = Foo()
b = Bar()
print(f.data_2) # --> abc
print(b.data_2) # --> abc
但我希望得到:
print(f.data_2) # --> abc
print(b.data_2) # --> def
uj5u.com熱心網友回復:
如果您不想像data上面有人指出的那樣接受作為 init func 的引數,這可以解決問題
class Foo(object):
def __init__(self):
self.data = "abc"
@property
def data_2(self):
return self.data
class Bar(Foo):
def __init__(self):
super(Bar, self).__init__()
self.data = "def"
f = Foo()
b = Bar()
print(f.data_2)
print(b.data_2)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/518061.html
下一篇:回傳分配值的屬性名稱的實體方法
