[英]Create child class object in parent class
像下面的例子一樣在父類中創建子類的對象是一個很好的設計,它似乎工作但它是一個很好的設計,有沒有更好的方法來做到這一點?
class parent(object):
def __init__(self):
print('Im running')
def execute(self):
x = child()
x.run()
x.myfun()
def myfun(self):
print('parent function')
def run(self):
print('parent running')
class child(parent):
def __init__(self):
super().__init__()
print('Im running too')
def run(self):
print('child running')
f = parent()
f.execute()
對於您的問題,這絕對不是一個好的設計,通常也不是一個好的設計(我想不出任何例外),並且絕對違反 OOP 設計和 SOLID 原則。
只是在 OOP 設計或任何其他軟件工程思維框架中,您需要明確的關系。 這使得您的父類和子類之間的關系本質上更加復雜。 更不用說大多數其他語言(至少是運行編譯代碼的語言)不允許這樣的事情發生。
如果您需要在另一個中擁有一個實例,反之亦然,那么繼承可能是錯誤的模式,因為您的類似乎以雙向方式連接,這與使用繼承的場景不同。
execute
根本不使用self
的事實表明它應該是一個類方法,在這種情況下,您可以使用實際提供的任何類來實例化x
。
一旦你這樣做了, Parent
的定義就不再依賴於任何特定的子類; 事實上,它不依賴於一個事實,即Parent
在所有子類; Parent.execute()
將繼續工作。
例如,
class Parent:
def __init__(self):
print('Im running')
@classmethod
def execute(cls):
x = cls()
x.run()
x.myfun()
def myfun(self):
print('parent function')
def run(self):
print('parent running')
class Child(Parent):
def __init__(self):
super().__init__()
print('Im running too')
def run(self):
print('child running')
Child.execute()
這將輸出
Im running
Im running too
child running
parent function
由於Child.execute
沒有定義,它解析為Parent.execute
。 但是Child
仍然是第一個通過的參數。 因此, x
將是Child
的實例,而不是Parent
。 x.run()
因此運行Child.run
,但x.myfun()
運行Parent.myfun
。
但是, Parent.execute
仍然依賴於x
具有特定於cls
的屬性這一事實表明您應該推遲限制execute
以僅使用Parent
定義的內容,並讓子覆蓋execute
以添加任何特定於子的行為。
或者, execute
應該是一個實例方法,但它應該簡單地調用self.fun
,將負擔放在調用者身上,以使用適當的對象調用execute
。
c = Child()
c.execute()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.