python四十二:类和对象
生活随笔
收集整理的這篇文章主要介紹了
python四十二:类和对象
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
類有數據屬性和函數屬性, 但對象只有數據屬性。?
def funName(args):'函數文檔字符串'函數體class 類名:'類的文檔字符串'類體創建一個類class foo:pass用類foo實例化一個對象f = foo()實例化干了什么事??
def dog(name, type, sex): # dog就是類 把一類事物相同的特征和動作整合到一起def run(dog):print("一條狗[%s],正在飛跑." % dog["name"])def eat(dog):print("一條狗[%s],正在啃骨頭." % dog["name"])def init(name, type, sex):dog1 = {"name": name,"type": type,"sex": sex,"run": run,"eat":eat}return dog1return init(name, type, sex)d1 = dog("旺財","藏獒","公") # d1就是對象 d1["eat"](d1)d2 = dog("小白","牧羊犬","母") d2["run"](d2)可以通過def實現面向對象,也可以通過class實現面向對象. ?要理解面向對象思想. 即使使用c語言也可以是實現面向對象設計
class Dog:def __init__(self, name, gender, type):self.name = nameself.gender = gender,self.type = type# 會自動將self返回def run(self):print("一條狗[%s],正在飛跑." % self.name)def eat(self):print("一條狗[%s],正在啃骨頭." % self.name)d1 = Dog("旺財","藏獒","公") d1.run()d2 = Dog("小白","牧羊犬","母") d2.eat()?
# 類相關知識 class China:'這是一個類'capital = "北京" # 數據屬性 靜態變量def develop(self): # 函數屬性 也可以稱為方法print("中國國立發展很快")def log():print("登錄月球成功")print(dir(China)) # 查看類的屬性 print(China.__dict__) # 查看類的屬性字典print(China.capital) # 取 __dict__字典['capital']的數據 print(China.__dict__['capital'])China.log() China.__dict__['log']() print(China.__base__) # 所有類都有一個共同的祖先:object print(China.__bases__) # 以元祖的形式 print(China.__module__) # 類所在的模塊 print(China.__class__) # 實例所對應的類?
增刪改查類數據屬性,函數屬性
class Fish:name = "魚" #靜態變量def __init__(self, type):self.type = typedef swim(self):print("正在海里游泳")def eat(self):print("正在吃食")f = Fish("鯨魚")# 數據屬性 # 查看類屬性 print(Fish.name)# 修改類屬性 Fish.name = "一條魚" print(Fish.name)# 增加類屬性 Fish.home = "水" print(Fish.home)# 修改類屬性 del Fish.name # print(Fish.name) 會報錯 AttributeError: type object 'Fish' has no attribute 'name'print(f.home) print(Fish.__dict__)# 函數屬性 # 增加函數屬性 def sleep():print("魚正在睡覺..")Fish.sleep = sleep # 增加一個函數屬性 Fish.sleep()# 修改函數屬性 def eat_food():print("魚正在歡快的吃食")Fish.eat = eat_fooddel Fish.swim # 刪除函數屬性 # f.swim() 調用報錯增刪改查實例數據屬性
class Fish:name = "魚" #靜態變量def __init__(self, type):self.type = typedef swim(self):print("正在海里游泳")def eat(self):print("正在吃食")f = Fish("鯨魚") f2 = Fish("鯊魚") # 實例數據屬性增刪改查 # 查看 print(f.name) print(f.eat) f.eat()# 增加 f.age = 1 print(f.age) # age屬性只增加在f實例中 #print(f2.age)# 修改 f.age = 2 print(f.age)# 刪除 del f.age #print(f.age) print(f.__dict__)? 實例,類中的數據屬性同名
class Fish:name = "魚" #靜態變量def __init__(self, type):self.type = typef = Fish("鯊魚") print(f.name,f.type) print(f.__dict__) f.name = "烏魚" # 將name添加到f實例自己的__dict__字典中,與類沒有關系 print(f.__dict__) print(f.name, Fish.name)?
注意點:
??
name = "魚" #靜態變量 class Fish:def __init__(self, type):self.type = type# 不是通過 實例名.name 或 類名.name調用屬性的,就不從__dict__字典中找# 找到類外面的作用域中的nameprint("----",name) f = Fish("鯊魚") name = "魚" class Fish:name = "大魚"def __init__(self, type):self.type = type# 不是通過 實例名.name 或 類名.name調用屬性的,就不從__dict__字典中找# 找到類外面的作用域中的nameprint("----",name)f = Fish("鯊魚")?
總結
以上是生活随笔為你收集整理的python四十二:类和对象的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python四十一:hashlib模块
- 下一篇: ORACLE TNS(transpare