我試圖讓類繼承父類的屬性。
主要類是Country,具有國家首都和總統兩個屬性。
State類派生自Country,應具有州首府和州長的屬性。
County 類派生自State,并且應該具有縣名的屬性。
我對類有一個非常基本的了解,任何幫助將不勝感激。
這是我擁有的代碼:注意:如果name = 'main': 可以更改,則下面沒有任何內容
class Country:
def __init__(self, country_capital, president):
self.country_capital = country_capital
self.president = president
class State(Country):
def __init__(self, state_capital, governor, c):
self.state_capital = state_capital
self.governor = governor
c = Country()
class County(State):
def __init__(self, county_seat, c):
self.county_seat = county_seat
c = State()
self.governor = super().__init__(self, state_capital)
if __name__ == '__main__':
United_States = Country("Washington, DC", "Joe Biden")
Kentucky = State("Frankfort", "Andy Beshear", United_States)
Jefferson = County("Louisville", Kentucky)
print("County seat: ", Jefferson.county_seat)
print(" Governor: ", Jefferson.governor)
print("State capital: ", Jefferson.state_capital)
print("Country capital: ", Jefferson.country_capital)
print("President:", Jefferson.president)
uj5u.com熱心網友回復:
由于您將“父”物件與“子”分開構造,因此我可能會建議組合而不是繼承。請注意,繼承意味著“is a”關系而不是“has a”關系——說 aState 是 a Country或 aState 具有 a Country它所在的關系是否正確?
class Country:
def __init__(self, capital: str, president: str):
self.capital = capital
self.president = president
class State:
def __init__(self, capital: str, governor: str, country: Country):
self.capital = capital
self.governor = governor
self.country = country
class County:
def __init__(self, seat: str, state: State):
self.seat = seat
self.state = state
self.country = state.country
if __name__ == '__main__':
United_States = Country("Washington, DC", "Joe Biden")
Kentucky = State("Frankfort", "Andy Beshear", United_States)
Jefferson = County("Louisville", Kentucky)
print("County seat: ", Jefferson.seat)
print("Governor: ", Jefferson.state.governor)
print("State capital: ", Jefferson.state.capital)
print("Country capital: ", Jefferson.country.capital)
print("President:", Jefferson.country.president)
uj5u.com熱心網友回復:
您需要像這樣在建構式中初始化超類:
class Country:
def __init__(self, country_capital, president):
self.country_capital = country_capital
self.president = president
class State(Country):
def __init__(self, state_capital, governor, country_capital, president):
super().__init__(country_capital, president)
self.state_capital = state_capital
self.governor = governor
class County(State):
def __init__(self, county_seat, state_capital, governor, country_capital, president):
super().__init__(self, state_capital, governor, country_capital, president)
self.county_seat = county_seat
然而,這并不是繼承的自然使用。您可能會考慮僅將州存盤為縣的屬性,而不是其超類。與州和國家相同。
uj5u.com熱心網友回復:
在使用繼承時,我們應該采用“是”的心態。這對您的代碼不太有意義,因為 State不是Country,因此它不會具有相同的屬性。
你應該使用屬性來表示一個州有一個國家是(就像你有)的一部分
要回答您的問題, usingsuper(). __init__()將初始化與父級相同的屬性,前提是它們在父級的建構式中進行了初始化。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/523043.html
標籤:Python班级
