如何更改对象的值?

时间:2017-10-23 19:46:27

标签: python class object

我必须创建一个类,其中有一个函数可以修改对象中变量的值。 班级狗:

class dog:

    def __init__(self,x,y,z):
        self.x=x
        self.y=y
        self.z=z
    def __str__(self):

       return print("mi nombre es "+self.x)
    def bark(self,otr):
        if self.z*self.y>otr.z*otr.y:
            print("gano: "+self.x)

            int(otr.x)=int(otr.x)-2

        if self.z*self.y<otr.z*otr.y:
            print("gano: "+otr.x)

            int(self.x)=int(self.x)-2

但是当我尝试运行它时,它给了我一个“无法调用函数来调用”错误,我也想知道这是否是正确的方法

1 个答案:

答案 0 :(得分:0)

我刚刚修改了你的狗课。请在下面的代码中查看我的修改和评论: -

class dog:
def __init__(self,x,y,z):
    self.x=x
    self.y=y
    self.z=z

def __str__(self):
    return print("mi nombre es "+self.x)    

def bark(self,otr):
    if self.z*self.y>otr.z*otr.y:
        print("gano: "+self.x)
        otr.x = int(otr.x)-2
    if self.z*self.y<otr.z*otr.y:
        print("gano: "+otr.x)
        self.x = int(self.x)-2 #what were you doing by int(self.x) on the left hand site which I removed. Don't do anything randomly. you need to understand what you are doing. For example - int(val) here val will be converted into integer from any value like string, double etc. Hence left hand side it does not mean anything.