日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python Day28

發布時間:2024/4/15 python 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python Day28 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

面對對象進階:

  1.反射

    

    1 什么是反射

      反射的概念是由Smith在1982年首次提出的,主要是指程序可以訪問、檢測和修改它本身狀態或行為的一種能力(自省)。

?

    2 python面向對象中的反射:通過字符串的形式操作對象相關的屬性。python中的一切事物都是對象(都可以使用反射)

?

          四個可以實現自省的函數

?

          下列方法適用于類和對象(一切皆對象,類本身也是一個對象)

?

hasattr

?

?

def hasattr(*args, **kwargs): # real signature unknown"""Return whether the object has an attribute with the given name.This is done by calling getattr(obj, name) and catching AttributeError."""passhasattr

 getattr

def getattr(object, name, default=None): # known special case of getattr"""getattr(object, name[, default]) -> valueGet a named attribute from an object; getattr(x, 'y') is equivalent to x.y.When a default argument is given, it is returned when the attribute doesn'texist; without it, an exception is raised in that case."""passgetattr

 ?setattr

def setattr(x, y, v): # real signature unknown; restored from __doc__"""Sets the named attribute on the given object to the specified value.setattr(x, 'y', v) is equivalent to ``x.y = v''"""passsetattr

 delattr

def delattr(x, y): # real signature unknown; restored from __doc__"""Deletes the named attribute from the given object.delattr(x, 'y') is equivalent to ``del x.y''"""passdelattr

四個方法的使用演示

class Foo:f = '類的靜態變量'def __init__(self,name,age):self.name=nameself.age=agedef say_hi(self):print('hi,%s'%self.name)obj=Foo('egon',73)#檢測是否含有某屬性 print(hasattr(obj,'name')) print(hasattr(obj,'say_hi'))#獲取屬性 n=getattr(obj,'name') print(n) func=getattr(obj,'say_hi') func()print(getattr(obj,'aaaaaaaa','不存在啊')) #報錯#設置屬性 setattr(obj,'sb',True) setattr(obj,'show_name',lambda self:self.name+'sb') print(obj.__dict__) print(obj.show_name(obj))#刪除屬性 delattr(obj,'age') delattr(obj,'show_name') delattr(obj,'show_name111')#不存在,則報錯print(obj.__dict__)四個方法的使用演示

類也是對象

class Foo(object):staticField = "old boy"def __init__(self):self.name = 'wupeiqi'def func(self):return 'func'@staticmethoddef bar():return 'bar'print getattr(Foo, 'staticField') print getattr(Foo, 'func') print getattr(Foo, 'bar')類也是對象

~__str__和__repr__

改變對象的字符串顯示__str__,__repr__

自定制格式化字符串__format__

#_*_coding:utf-8_*_ format_dict={'nat':'{obj.name}-{obj.addr}-{obj.type}',#學校名-學校地址-學校類型'tna':'{obj.type}:{obj.name}:{obj.addr}',#學校類型:學校名:學校地址'tan':'{obj.type}/{obj.addr}/{obj.name}',#學校類型/學校地址/學校名 } class School:def __init__(self,name,addr,type):self.name=nameself.addr=addrself.type=typedef __repr__(self):return 'School(%s,%s)' %(self.name,self.addr)def __str__(self):return '(%s,%s)' %(self.name,self.addr)def __format__(self, format_spec):# if format_specif not format_spec or format_spec not in format_dict:format_spec='nat'fmt=format_dict[format_spec]return fmt.format(obj=self)s1=School('oldboy1','北京','私立') print('from repr: ',repr(s1)) print('from str: ',str(s1)) print(s1)''' str函數或者print函數--->obj.__str__() repr或者交互式解釋器--->obj.__repr__() 如果__str__沒有被定義,那么就會使用__repr__來代替輸出 注意:這倆方法的返回值必須是字符串,否則拋出異常 ''' print(format(s1,'nat')) print(format(s1,'tna')) print(format(s1,'tan')) print(format(s1,'asfdasdffd')) class B:def __str__(self):return 'str : class B'def __repr__(self):return 'repr : class B'b=B() print('%s'%b) print('%r'%b)%s和%r

~__del__

析構方法,當對象在內存中被釋放時,自動觸發執行。

注:此方法一般無須定義,因為Python是一門高級語言,程序員在使用時無需關心內存的分配和釋放,因為此工作都是交給Python解釋器來執行,所以,析構函數的調用是由解釋器在進行垃圾回收時自動觸發執行的。

~__new__

class A:def __init__(self):self.x = 1print('in init function')def __new__(cls, *args, **kwargs):print('in new function')return object.__new__(A, *args, **kwargs)a = A() print(a.x) class Singleton:def __new__(cls, *args, **kw):if not hasattr(cls, '_instance'):orig = super(Singleton, cls)cls._instance = orig.__new__(cls, *args, **kw)return cls._instanceone = Singleton() two = Singleton()two.a = 3 print(one.a) # 3 # one和two完全相同,可以用id(), ==, is檢測 print(id(one)) # 29097904 print(id(two)) # 29097904 print(one == two) # True print(one is two)單例模式

~__call__

對象后面加括號,觸發執行。

注:構造方法的執行是由創建對象觸發的,即:對象 = 類名() ;而對于 __call__ 方法的執行是由對象后加括號觸發的,即:對象() 或者 類()()

?

class Foo:def __init__(self):passdef __call__(self, *args, **kwargs):print('__call__')obj = Foo() # 執行 __init__ obj() # 執行 __call__

?

~__len__

class A:def __init__(self):self.a = 1self.b = 2def __len__(self):return len(self.__dict__) a = A() print(len(a))

~__hash__

class A:def __init__(self):self.a = 1self.b = 2def __hash__(self):return hash(str(self.a)+str(self.b)) a = A() print(hash(a))

~__eq__

class A:def __init__(self):self.a = 1self.b = 2def __eq__(self,obj):if self.a == obj.a and self.b == obj.b:return True a = A() b = A() print(a == b) class Person:def __init__(self,name,age,sex):self.name = nameself.age = ageself.sex = sexdef __hash__(self):return hash(self.name+self.sex)def __eq__(self, other):if self.name == other.name and self.sex == other.sex:return Truep_lst = [] for i in range(84):p_lst.append(Person('egon',i,'male'))print(p_lst) print(set(p_lst))一道面試題

?

轉載于:https://www.cnblogs.com/liuduo/p/7576906.html

總結

以上是生活随笔為你收集整理的Python Day28的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。