Python学习---面向对象的学习[深入]
生活随笔
收集整理的這篇文章主要介紹了
Python学习---面向对象的学习[深入]
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
類的深入學習
?? a. Python中一切事物都是對象
??? b. class Foo:
??????????? pass???????
??????? obj = Foo()
??????? # obj是對象,Foo類
??????? # Foo類也是一個對象,type的對象
??? c. 類都是type類的對象?? type(..)
????? “對象”都是以類的對象 類()
??? d. 類實際上是type類型的對象,所有的類都是Object的子類
創建類的方法[2種]
# 第一種:類實際上是type類型的對象,所有的類都是Object的子類 Foo = type('Foo', (object,), {'func': 'function'})# 第二種: class Foo:def func(self):print(123) f = Foo() f.func()利用metaclass創建類: 必須繼承type類,同時init必須傳遞4個參數過去
必須繼承type類 ---代碼有誤--- class MyType(type): # the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases# 必須給出4個參數def __init__(self, *args, **kwargs): # __init__() takes 1 positional argument but 4 were givenprint('Mytype創建類對象')def __call__(self, *args, **kwargs): print('Mytype的call方法')def __new__(self, *args, **kwargs): print('Mytype的new方法') class Foo(object, metaclass=MyType):def func(self):print(123)# 創建對象后執行init方法def __new__(self, *args, **kwargs):print('Foo的new方法')return '返回Foo的對象' f = Foo() # 調用MyType的__init__方法,Foo是MyType的對象,Foo()會調用MyType的__call__方法 f.func() # Mytype創建類對象,這里是有MyType的# 123【轉載】類的創建原理圖:
異常處理
被動異常
try:pass except IndentationError as e:pass except ValueError as e: # 小的Exception放在Exception前面pass except Exception as e: # e是Exception的對象,封裝了Exception信息pass else: # 正常代碼正常,則執行else,否則執行else pass finally:pass # 出錯不出錯,一定要執行的代碼主動觸發異常: raise Exception("Sorry")
try:raise Exception("Sorry") except Exception as e:print(e)自定義異常:繼承Exception類來實現
class HhH(Exception):def __init__(self, msg):self.message = msgdef __str__(self):return self.message # 這里只需要返回就可以了,不能直接打印 try:raise HhH('hhh, Wrong') except HhH as e:print(e)?斷言assert
assert 比較的內容: 條件成立,則打印XXX,否則報錯
一般用強制用戶的服從,Java從1.2開始也添加了這個功能,但是一般實際中不用。Python源碼中有用到
assert 1 < 5 print('hhh')反射
1. 通過字符串操作對象的成員(方法,字段):
class Foo:def __init__(self, name, age):self.name = nameself.age = agedef fun(self):print('%s-%s' % (self.name, self.age))obj = Foo('ftl', 23) print(obj.name) b = 'name' print('obj.__dict__[b]:',obj.__dict__[b]) # 通過字典取值 print("getattr(obj, 'name'):",getattr(obj, 'name')) # 通過內置函數getattr取出值 fun = getattr(obj, 'fun') fun() setattr(obj, 'school', 'xupt') print(hasattr(obj, 'school')) print(delattr(obj, 'school'))模塊級別的反射:
class Foo():NAME = 'ftl'def hello(self):print('hello') print(getattr(Foo, 'NAME')) hello = getattr(Foo(), 'hello') # 取到函數的內存地址 print(hello) print(hello()) # 取到函數的對象單例模式
class Foo:__instance = Nonedef __init__(self, name, age):self.age = ageself.name = name@classmethod # 靜態方法def get_Instance(cls):if cls.__instance:return cls.__instanceelse:cls.__instance = Foo('hhh', 23)return cls.__instancedef show(self):print(self.age, self.name) obj = Foo.get_Instance() obj.show()【更多學習】
選課系統
面向對象編程更多參考
轉載于:https://www.cnblogs.com/ftl1012/p/9383687.html
總結
以上是生活随笔為你收集整理的Python学习---面向对象的学习[深入]的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一头扎进sql之多表操作
- 下一篇: python201811210作业4