如何在Python中使用类继承?

时间:2017-04-08 05:24:52

标签: python python-2.7 class

我应该创建一个名为Dog(Animal)的类,它继承自Class Animal。但是,在运行此代码后,我遇到了一些我不理解的错误:

问题解决了,我现在没有进一步的问题

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 get_height(self):
    return str(self.__height)

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

def get_sound(self):
    return self.__sound

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

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


cat = Animal('pussy', 33, 10, 'meow')
print(cat.toString())
print(cat.get_type())
print(cat.get_sound())

class Dog(Animal):
__owner = ""

def __init__(self, name, height, weight, sound, owner):
    self.__owner = owner
    super(Dog, self).__init__(name, height, weight, sound)

def set_owner(self, owner):
    self.__owner = owner

def get_owner(self):
    return self.__owner

def get_type(self):
    print("Dog") # Dog object

def toString(self):
    return "{} is {} cm tall and {} kilograms and says{} its owner is {}".format(self.__name,
                                                                                 self.__height,
                                                                                 self.__weight,
                                                                                 self.__sound,
                                                                                 self.__owner)

spot = Dog("kaili", 22, 33, "woof", "Jiahui") 
print(spot.toString())  

2 个答案:

答案 0 :(得分:1)

更改此行:

<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />;
<title>jQuery UI Datepicker - Default functionality</title>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.1/jquery.validate.min.js"></script>

到此:

class Animal:

post解释得非常好。

答案 1 :(得分:1)

在开头添加元类 =类型后,问题就解决了。我不太确定,但似乎元类允许python2.7访问python3的库。