如何更改对象的值?

2024-09-29 07:28:26 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

但当我试着运行它时,它会给我一个“cant assign function to call”错误,我也想知道这是否是正确的方法


Tags: 对象函数selfreturnifinitdefclass
1条回答
网友
1楼 · 发布于 2024-09-29 07:28:26

我刚刚修改了你的狗课。在代码中查看我的修改和注释below:- 你知道吗

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.

相关问题 更多 >