自學Python之路html
定義一個類的格式以下:python
class 類名: 方法列表
舉例1 : this
class Cat: #定義一個Cat類 #屬性 #方法 def eat(self): print("貓在吃魚....") def drink(self): print("貓正在喝kele.....")
舉例2:spa
class Car: # 定義一個Car類 # 屬性 # 方法 def getCarInfo(self): print('車輪子個數:%d, 顏色%s'%(self.wheelNum, self.color)) # 稍後介紹 def move(self): print("車正在移動...")
類不會自動執行,因而須要建立對象。3d
建立對象的格式爲: 指針
對象名 = 類()
舉例1:htm
class Cat: #屬性 #方法 def eat(self): print("貓在吃魚....") def drink(self): print("貓正在喝kele.....") #建立一個對象 tom = Cat()
舉例2:對象
class Car: # 定義一個Car類 # 屬性 # 方法 def getCarInfo(self): print('車輪子個數:%d, 顏色%s'%(self.wheelNum, self.color)) # 稍後介紹 def move(self): print("車正在移動...") #建立一個對象 BWM = Car()
舉例1 :blog
class Cat: #屬性 #方法 def eat(self): print("貓在吃魚....") def drink(self): print("貓正在喝kele.....") #建立一個對象 tom = Cat() #調用tom指向的對象中的方法 tom.eat() tom.drink()
舉例1 :內存
class Cat: #屬性 #方法 def eat(self): print("貓在吃魚....") def drink(self): print("貓正在喝kele.....") #建立一個對象 tom = Cat() #調用tom指向的對象中的方法 tom.eat() tom.drink() # 給tom指向的對象添加兩個屬性 tom.name = 「湯姆」 tom.age = 40
print("%的年齡是:%d"%(tom.name,tom.age))
class Cat: #屬性 #方法 def eat(self): print("貓在吃魚....") def drink(self): print("貓正在喝kele.....") def introduce(self): print("%的年齡是:%d"%(tom.name,tom.age)) #建立一個對象 tom = Cat() #調用tom指向的對象中的方法 tom.eat() tom.drink() # 給tom指向的對象添加兩個屬性 tom.name = 「湯姆」 tom.age = 40 #獲取屬性 tom.introduce()
class Cat: #屬性 #方法 def eat(self): print("貓在吃魚....") def drink(self): print("貓正在喝kele.....") def introduce(self): print("%的年齡是:%d"%(tom.name,tom.age)) #建立一個對象 tom = Cat() #調用tom指向的對象中的方法 tom.eat() tom.drink() # 給tom指向的對象添加兩個屬性 tom.name = 「湯姆」 tom.age = 40 #獲取屬性 tom.introduce() #建立另外一個對象 lanmao = Cat() #調用lanmao指向的對象中的方法 lanmao.eat() lanmao.drink() # 給lanmao指向的對象添加兩個屬性 lanmao.name = 「藍貓」 lanmao.age = 12 #獲取屬性 tom.introduce() lanmao.introduce()
這樣的結果確定不對,那是由於lanmao.introduce()調用內存的時候對應的是print("%的年齡是:%d"%(tom.name,tom.age)) ,那麼如何解決此問題???
class Cat: #屬性 #方法 def eat(self): print("貓在吃魚....") def drink(self): print("貓正在喝kele.....") def introduce(self): print("%的年齡是:%d"%(self.name,self.age)) #建立一個對象 tom = Cat() #調用tom指向的對象中的方法 tom.eat() tom.drink() # 給tom指向的對象添加兩個屬性 tom.name = 「湯姆」 tom.age = 40 #獲取屬性 tom.introduce() #建立另外一個對象 lanmao = Cat() #調用lanmao指向的對象中的方法 lanmao.eat() lanmao.drink() # 給lanmao指向的對象添加兩個屬性 lanmao.name = 「藍貓」 lanmao.age = 12 #獲取屬性 tom.introduce() lanmao.introduce()
self總結:
......