類
類是抽象的模板付枫,用來描述具有相同屬性和方法的對象的集合滞时,比如Animal類。 類名通常采用駝峰式命名方式卖宠,盡量讓字面意思體現(xiàn)出類的作用巍杈。
圖片.png
Python使用class關鍵字來定義類,其基本結構如下:
class 類名(父類列表):
pass
類的構成
類(class)由3個部分構成
類的名稱:類名
類的屬性:一組數(shù)據(jù)
類的方法:允許對進行操作的方法
人類的設計:
事物名稱(類名):人(Person)
屬性:身高(height)扛伍、年齡(age)
方法:跑(run)筷畦、吃(eat)
定義一個類
class People:
# 屬性
# 方法
def eat(self):
print("人在吃....")
def drink(self):
print("人在喝.....")
定義類時有2種:新式類和經(jīng)典類,上面的People為經(jīng)典類刺洒,如果是People(object)則為新式類
類名 的命名規(guī)則按照"大駝峰"
創(chuàng)建對象
tom = People()
調用對象的方法
class Cat:
# 屬性
# 方法
def eat(self):
print("貓在吃....")
def drink(self):
print("貓在喝")
tom = Cat()
# 調用tom指向的對象中的方法
tom.eat()
tom.drink()
給對象添加屬性
屬性簡單來說鳖宾,就是變量。
# 給tom指向的對象添加2個屬性
tom.name = "湯姆"
tom.age = 18
獲取屬性的方法
class Cat:
# 屬性
# 方法
def eat(self):
print("貓在吃....")
def drink(self):
print("貓在喝")
def info(self):
print("%s的年齡是:%d"%(tom.name,tom.age))
tom = Cat()
tom.name = "湯姆"
tom.age = 18
# print("%s的年齡是:%d"%(tom.name,tom.age))
tom.info()
lanmao = Cat()
lanmao.name = "藍貓"
lanmao.age = 20
lanmao.info()
init方法
調用對象時自動執(zhí)行的一個方法逆航。也稱之為魔法方法
class Cat:
# 初始化對象
def __init__(self,new_name,new_age):
self.name = new_name
self.age = new_age
# 方法
def eat(self):
print("貓在吃....")
def drink(self):
print("貓在喝")
def info(self):
print("%s的年齡是:%d"%(self.name,self.age))
tom = Cat("湯姆",18)
# tom.name = "湯姆"
# tom.age = 18
tom.info()
lanmao = Cat()
# lanmao.name = "藍貓"
# lanmao.age = 20
lanmao.info()
str方法
class Cat:
# 初始化對象
def __init__(self,new_name,new_age):
self.name = new_name
self.age = new_age
def __str__(self):
return "%s的年齡是:%d"%(self.name,self.age)
# 方法
def eat(self):
print("貓在吃....")
def drink(self):
print("貓在喝")
def info(self):
print("%s的年齡是:%d"%(self.name,self.age))
tom = Cat("湯姆",18)
print(tom)
(寫在最后鼎文,由于以后每天晚上九點半之后會更新Python基礎的知識點,記得來看哦R蚶)
此文來源于微博和今日頭條:邏二妞拇惋,轉載請注明出處,謝謝