python 魔法方法補充(__setattr__,__getattr__,__getattribute__)


python 魔法方法補充


1 getattribute (print(ob.name) -- obj.func())當訪問對象的屬性或者是方法的時候觸發

	class F(object):
	
	    def __init__(self):
	        self.name = 'A'
	
	    def hello(self):
	        print('hello')
	
	    def __getattribute__(self, item):
	        print('獲取屬性,方法',item)
	        return object.__getattribute__(self,item)
	
	a = F()
	print(a.name)
	a.hello()
	
	
	獲取屬性,方法 name
	A
	獲取屬性,方法 hello
	hello

2 getattr 攔截運算(obj.xx),對沒有定義的屬性名和實例,會用屬性名作為字符串調用這個方法

	class F(object):
	    def __init__(self):
	        self.name = 'A'
	
	    def __getattr__(self, item):
	        if item == 'age':
	            return 40
	        else:
	            raise AttributeError('沒有這個屬性')
	
	f = F()
	print(f.age)
	
	# 40

3 setattr 攔截 屬性的的賦值語句 (obj.xx = xx)

class F(object):

    def __setattr__(self, key, value):
        self.__dict__[key] = value

a = F()
a.name = 'alex'
print(a.name)

如何自定義私有屬性:

class F(object):  # 基類--定義私有屬性
    def __setattr__(self, key, value):
        if key in self.privs:
            raise AttributeError('該屬性不能改變')
        else:
            self.__dict__[key] = value


class F1(F):
    privs = ['age','name']  # 私有屬性列表

    # x = F1()
    # x.name = 'egon'  # AttributeError: 該屬性不能改變
    # x.sex = 'male'


class F2(F):
    privs = ['sex']      # 私有屬性列表
    def __init__(self):
        self.__dict__['name'] = 'alex'

        # y = F2()
        # y.name = 'eva'

getitem , setitem, delitem

class F(object):

	def __getitem__(self,item):
		print(item)

	def __setitem__(self,key,value):
		print(key,value)

	def __delitem__(self,key):
		print(key)


f  = F()

f['b']
f['c'] = 1
del f['a']


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM