1.關於類
#關於類的定義
class Animal(object):
species="Animal"#類變量
def __init__(self, name):#類的構造函數
self.name=name#定義並賦值類變量
self.attributes=[]#定義並賦值類變量
def add_attributes(self,attributes):#類中的方法與一般函數方法不同之處就是包含一個“self”指針。
if(type(attributes)==list):
self.attributes.extend(attributes)#加入新列表
else:
self.attributes.append(attributes)#加入新元素
def __str__(self):#代表類的字符串
return self.name+"is of type "+self.species+" and has attributes:"+str(self.attributes)
a1=Animal("Sheep")
a1.add_attributes(["run","eats","grass"])
print(str(a1))#調用初始化字符串
2.關於類繼承
#類的繼承
class Dog(Animal):
species="Dog"
def __init__(self, *args):#定義構造函數
super(Dog,self).__init__(*args)#super代表基類。使用super不需要明確給出基類的名稱。方便修改代碼。
class Fox(Animal):
species="Fox"
def __init__(self, *args):
super(Fox,self).__init__(*args)
d1=Dog("Rover")
d1.add_attributes(["lazy","beige","sleeps","eats"])
print(str(d1))
f1=Fox("Gerky")
f1.add_attributes(["clever","sly","beautiful","brown"])
print(str(f1))
print(type(f1))
3.輸出: