创建课程遵循哪种策略?

llr*_*lrs 5 python class

我正在努力学习课程的运作方式.我想用一些共享元素创建不同的类而不是其他类,但据我所知,我可以通过三种不同的方式创建它:

  • 创建一个包含所有共享元素的类,然后继承此类并修改新类中的特定方法和属性.像这样的东西:

     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.
    
    Run Code Online (Sandbox Code Playgroud)
  • 创建一个类并询问一种类,并更改从中获取输入的对象的定义.像这样的东西:

    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
    
    Run Code Online (Sandbox Code Playgroud)
  • 创建两个不同的类,然后执行多重继承:

    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):
    
    Run Code Online (Sandbox Code Playgroud)

我看到第一个是简单的,让我可以更灵活地创建具有共享方法和属性的多个类.但第二个在我看来更容易使用(或者至少我喜欢它),我可以if随心所欲地摆脱条件.并且第三个可以用于混合不同类而没有任何共享方法或属性,并且如果它们共享它不会弄乱它(或者它会?).

哪一个更好?
但是关于以一种或另一种方式写作,似乎只是关于你如何想要你的代码的策略问题.它是否正确?

jon*_*rpe 2

第二个例子不是一个好主意;这会导致大量重复的代码,并且Enemy每次你想出一种新类型的敌人角色时,你都必须编辑你的类。

在第一个和第三个之间进行选择比较棘手,并且取决于您想要实现的目标(“策略问题”,正如您所拥有的那样)。

第一个是来自EnemyforTroll和 的单一继承Goblin,它很有用,因为它允许您定义所有字符一次具有的所有代码,并且仅定义和类Enemy中的差异。您可以进一步扩展它,并从超类(或元类)继承,它为和类(例如,, ...)提供了真正基本的东西。TrollGoblinEnemyCharacterEnemyHeronamehealth

class Enemy(Character)

class Troll(Enemy)
Run Code Online (Sandbox Code Playgroud)

如果您想分离角色和角色,第三个示例可能很有用,例如您可以

class FriendlyTroll(Troll, Friend)
Run Code Online (Sandbox Code Playgroud)

class UnfriendlyTroll(Troll, Enemy)
Run Code Online (Sandbox Code Playgroud)

如果这些角色意味着不同的实例属性(例如,Friend混合可能会引入一种share方法)。这允许您的字符定义更加复杂,但是如果您不打算使用额外的功能,那么您的头脑就会变得很复杂,并且可能会导致棘手的多重继承问题。

TL;DR:使用第一个!如果您稍后决定确实需要将角色分离到混合类中,那么这并不是一项太复杂的任务。