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))

輸出的結果是:

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