如何管理对类实例的更改仅限于该实例

时间:2019-02-23 17:15:06

标签: python oop

我正在尝试完成命运之轮代码。这是我拥有的对象的方案:`

class WOFPlayer: 

    def __init__(self,name, prizes = []):
        self.name = name
        self.prizes = prizes

    def addPrize(self, prize):
        self.prizes.append(prize)


class WOFHumanPlayer(WOFPlayer):

    def __init__(self,name):
      WOFPlayer.__init__(self,name) 


class WOFComputerPlayer(WOFPlayer):

    def __init__(self,name, difficulty):
      WOFPlayer.__init__(self,name)
      self.difficulty = difficulty

h1 = WOFHumanPlayer('John')
h2 = WOFHumanPlayer('Steve')
c1 = WOFComputerPlayer('GX625',3)

c1.addPrize('gold')
print(h1.prizes)
print(h2.prizes)
print(c1.prizes)`

我看到,如果我在实例c1上运行addPrize,它将应用于所有其他实例,因此h1,h2和c1都将具有奖项= ['gold']属性,这并不是我所清楚知道的打算。在我看来,正确的方法也是在子类的构造函数中定义奖赏,如下所示:

class WOFHumanPlayer(WOFPlayer):

    def __init__(self,name):
      WOFPlayer.__init__(self,name) 
      self.prizes = []

class WOFComputerPlayer(WOFPlayer):

    def __init__(self,name, difficulty):
      WOFPlayer.__init__(self,name)
      self.difficulty = difficulty
      self.prizes = []

这可以解决我的实例案例的问题。但是,当我在Coursera课程的测试用例中运行它时,它仍然给我以下错误:addPrize更改了其他实例。因此,我怀疑还有其他示例丢失了,而我的解决方案还没有到此为止。有什么更好的方法来纠正此问题? OOP也非常新手,因此相关的参考读物对我也将很有用。

0 个答案:

没有答案