python四十二:類和物件
阿新 • • 發佈:2018-11-04
類有資料屬性和函式屬性, 但物件只有資料屬性。
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 dog1 return 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 = name self.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 = type
def 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_food
del Fish.swim # 刪除函式屬性
# f.swim() 呼叫報錯
增刪改查例項資料屬性
class Fish:
name = "魚" #靜態變數
def __init__(self, type):
self.type = type
def 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 = type
f = 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__字典中找
# 找到類外面的作用域中的name
print("----",name)
f = Fish("鯊魚")
name = "魚"
class Fish:
name = "大魚"
def __init__(self, type):
self.type = type
# 不是通過 例項名.name 或 類名.name呼叫屬性的,就不從__dict__字典中找
# 找到類外面的作用域中的name
print("----",name)
f = Fish("鯊魚")