python类属性、实例、实例变量、继承的综合练习

这是一个关于类的综合练习。包含的知识点有类变量与实例变量;初始化函数;类的内置函数介绍;str()将数字和列表变成字符串;为实例增加类变量;类的继承等内容。

class Animal:
    "Object about Animal."#内置函数__doc__ 所显示的内容
    kind="animal"#类方法,静态变量
    def __init__(self,name):
        self.name=name
        self.attr=[]#设定属性,属性就是属于一个对象的数据或者函数元素
    def add_attributes(self,attri):#添加属性方法
        if(type(attri)==list):#判断是否为列表
            self.attr.extend(attri)#增加新列表
        else:
            self.attr.append(attri)#增加列表元素
    def __str__(self):
        return "Animal: "+self.name+" has attributes: "+str(self.attr)#数字、列表变成字符串要用str()函数

print(Animal.__name__)#显示类名称
print(Animal.__module__)#显示模块
print(Animal.__doc__)#显示类注释(类名称下面)
print(Animal.__dict__)#显示类的所有属性方法
print(Animal.__bases__)#显示基类
print("——————————————————————————")
ani=Animal("Cat")
catAttri=["clever","lovely","soft"]
ani.add_attributes(catAttri)
print(str(ani))
print("——————————————————————————")
ani.count=0#增加实例变量
print(ani.__dict__)#显示所有实例变量
print("——————————————————————————")
#类的继承
class Dog(Animal):
    "This is Dog derived from Animal."
    species="Dog"
    def __init__(self,*args):
        super(Dog,self).__init__(*args)
class Fox(Animal):
    "This is Fox derived from Animal."
    species="Fox"
    def __init__(self,*args):
        super(Fox,self).__init__(*args)
print("——————————————————————————")
print(Dog.__dict__)
d1=Dog("ROVER")
d1.add_attributes(["lazy","beige","sleeps","eats"])
print(str(d1))
print(d1.__dict__)
print("——————————————————————————")
f1=Fox("Gerky")
f1.add_attributes(["clever","sly","beautiful","brown"])
print(str(f1))

输出的结果是:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章