这个构造函数不带参数:python

时间:2016-04-04 19:59:20

标签: python class

import random
import sys
import os

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

def __init__(self, name, height, weight, sound):
    self.__name=name
    self.__height=height
    self.__weight=weight
    self.__sound=sound

def set_name(self,name):
    self.__name =name
def get_name(self):
    return self.__name
def set_height(self,height):
    self.__height =height
def get_height(self):
    return str(self.__height)
def set_weight(self,weight):
    self.__weight =weight
def get_weight(self):
    return str(self.__weight)
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 {} kilograms and say{}".format(self.__name, self.__height,self.__weight,self.__sound)
cat = Animal('ruby',33,10,'meow')
print(cat.toString())

错误讯息:

Traceback (most recent call last):
  File "python", line 37, in <module>
TypeError: this constructor takes no arguments

2 个答案:

答案 0 :(得分:1)

类方法应该缩进到类

import random
import sys
import os

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

    def __init__(self, name, height, weight, sound):
        self.__name=name
        self.__height=height
        self.__weight=weight
        self.__sound=sound

    def set_name(self,name):
        self.__name =name
    def get_name(self):
        return self.__name
    def set_height(self,height):
        self.__height =height
    def get_height(self):
        return str(self.__height)
    def set_weight(self,weight):
        self.__weight =weight
    def get_weight(self):
        return str(self.__weight)
    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 {} kilograms and say{}".format(self.__name, self.__height,self.__weight,self.__sound)
cat = Animal('ruby',33,10,'meow')
print(cat.toString())

这导致

ruby is 33 cm tall and 10 kilograms and saymeow

答案 1 :(得分:0)

类必须在一个块中定义。此外,不建议使用吸气剂和吸气剂。应该删除类属性,因为它们被设置为实例属性。 动物类:     类型=“动物”     def __init __(自己,姓名,身高,体重,声音):         self.name =名称         self.height =高度         自重=体重         self.sound =声音     def __str __():         返回“ {0.name}高{0.height}厘米,{0.weight}公斤,说{0.sound}”。     猫=动物('红宝石',33,10,'喵')     打印(猫)