我想了解課程是如何工作的。我想有一些共同的元素和其他人不能創造不同的類,但據我所知,我可以從三種不同方式創建:創建課程遵循哪種策略?
與所有共享元素創建一個類,然後繼承這個類並修改新類中的具體方法和屬性。類似的東西:
class Enemy(object): """Enemy!""" def __init__(self, damage=30, life=100, enemy="Hero"): #And keep defining the class and its methods and attributes in common with all the enemys class Troll(Enemy): """Troll!""" def __init__ (self, defense=0): #And define the specific attributes and methods for Trolls.
創建一個類,並要求類型的類,並改變從輸入它得到了對象的定義。類似的東西:
class Enemy(object): """Enemy!""" def __init__(self, damage=30, defense=0, life=100, type="Troll" enemy="Hero"): if type=="Troll": #Do that for type "Troll" if type=="Goblin": #Do that for type "Goblin" #And keep defining the class and its methods and attributes for each accepted type
創建兩個不同的類,然後做多重繼承:
class Enemy(object): """Enemy!""" def __init__(self, damage=30, life=100, enemy="Hero"): #And keep defining the class and its methods and attributes in common with all the enemys class Trolls(object): """Trolls!""" def __init__ (self, defense=1, shield=20): #And define the specific attributes and methods for Trolls. class SuperTroll(Enemy, Trolls):
我看到的第一個是最簡單的一個,讓我可以更靈活地創建多個具有共享方法和屬性的類。但第二個在我看來更容易使用(或者至少我喜歡它),並且無論我想要什麼條件,我都可以跳出if
條件。第三種方法對於混合不同的類沒有任何共享的方法或屬性是可行的,如果它們共享它不會弄亂它(或者它會?)。
哪一個更好?
但是關於以某種方式編寫代碼似乎只是一個關於如何實現代碼的策略問題。 這是正確的嗎?
第二個不是面向對象的。當你想添加新的敵人類型時,你會做什麼?你希望能夠在不改變基類的情況下創建一個新的 – Elisha
我很困惑你的第三種方法。爲什麼要有「Trolls」類和「Troll」類?有什麼不同? – Kevin
我正要推薦對抗第三名,但意識到它有一個有用的區別:「敵人」是一個角色,可以應用於各種種族。 「巨魔」是一個種族,但可能會有「朋友」巨魔和「敵人」巨魔。也就是說,這意味着一個更爲豐富的階級體系似乎是必要的,所以我會推薦第一種方法。 – chepner