繁体   English   中英

TypeError:object()不带参数-python

[英]TypeError: object () takes no parameters - python

我是python的新手,正在尝试使用类和对象编写程序。 以下是我的代码:

class Animal:
    __name = ""
    __height = 0
    __weight = 0
    __sound = 0

# define a constructor and pass arguments
def __init__(self, name, height, weight, sound):
    self.__name = name
    self.__height = height
    self.__weight = weight
    self.__sound = sound


# set and get functions for name
def set_name(self, name):
    self.__name = name

def get_name(self):
    return self.__name


# set and get functions for height
def set_height(self, height):
    self.__height = height

def get_height(self):
    return str(self.__height)


# set and get functions for weight
def set_weight(self, weight):
    self.__weight = weight


def get_weight(self):
    return str(self.__weight)


# set and get functions for sound
def set_sound(self, sound):
    self.__sound = sound

def get_sound(self):
    return self.__sound


def get_type(self):
    print("Animal")


def toString(self):
    return "{} is {} cm tall and {} kg and say {}".format(self.__name, self.__height, self.__weight, self.__sound)


# create an object call cat of type Animal
cat = Animal('Whiskers', 33, 10, 'Meow')
print(cat.toString())

当我运行程序时,它给我一个错误,即对象没有参数。 但是我已经在类的构造函数中描述了参数。 请帮忙。

确保正确地缩进了Animal的所有功能。 他们必须在Animal类中

就像其他人提到的那样, __init__方法需要在Animal类中缩进,以使其被视为构造函数。

但是,执行此操作后要小心。 现在声明__name__height__weight__sound方式是静态类变量。 但是,在__init__ (通过在变量前面加上self. ),您将使用名称变量名称重新声明实例变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM