Python学习---面向对象的学习[深入]
類的深入學(xué)習(xí)
?? a. Python中一切事物都是對象
??? b. class Foo:
??????????? pass???????
??????? obj = Foo()
??????? # obj是對象,Foo類
??????? # Foo類也是一個對象,type的對象
??? c. 類都是type類的對象?? type(..)
????? “對象”都是以類的對象 類()
??? d. 類實際上是type類型的對象,所有的類都是Object的子類
創(chuàng)建類的方法[2種]
# 第一種:類實際上是type類型的對象,所有的類都是Object的子類 Foo = type('Foo', (object,), {'func': 'function'})# 第二種: class Foo:def func(self):print(123) f = Foo() f.func()利用metaclass創(chuàng)建類: 必須繼承type類,同時init必須傳遞4個參數(shù)過去
必須繼承type類 ---代碼有誤--- class MyType(type): # the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases# 必須給出4個參數(shù)def __init__(self, *args, **kwargs): # __init__() takes 1 positional argument but 4 were givenprint('Mytype創(chuàng)建類對象')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)# 創(chuàng)建對象后執(zhí)行init方法def __new__(self, *args, **kwargs):print('Foo的new方法')return '返回Foo的對象' f = Foo() # 調(diào)用MyType的__init__方法,Foo是MyType的對象,Foo()會調(diào)用MyType的__call__方法 f.func() # Mytype創(chuàng)建類對象,這里是有MyType的# 123【轉(zhuǎn)載】類的創(chuàng)建原理圖:
異常處理
被動異常
try:pass except IndentationError as e:pass except ValueError as e: # 小的Exception放在Exception前面pass except Exception as e: # e是Exception的對象,封裝了Exception信息pass else: # 正常代碼正常,則執(zhí)行else,否則執(zhí)行else pass finally:pass # 出錯不出錯,一定要執(zhí)行的代碼主動觸發(fā)異常: raise Exception("Sorry")
try:raise Exception("Sorry") except Exception as e:print(e)自定義異常:繼承Exception類來實現(xiàn)
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 比較的內(nèi)容: 條件成立,則打印XXX,否則報錯
一般用強(qiáng)制用戶的服從,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')) # 通過內(nèi)置函數(shù)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') # 取到函數(shù)的內(nèi)存地址 print(hello) print(hello()) # 取到函數(shù)的對象單例模式
class Foo:__instance = Nonedef __init__(self, name, age):self.age = ageself.name = name@classmethod # 靜態(tài)方法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()【更多學(xué)習(xí)】
選課系統(tǒng)
面向?qū)ο缶幊谈鄥⒖?/p>
轉(zhuǎn)載于:https://www.cnblogs.com/ftl1012/p/9383687.html
總結(jié)
以上是生活随笔為你收集整理的Python学习---面向对象的学习[深入]的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一头扎进sql之多表操作
- 下一篇: websocket python爬虫_p