天天看點

python中類的特殊成員

class foo:
    def __init__(self):
        print('init')

    def __call__(self, *args, **kwargs):
        print('call')

    def __del__(self):
        print('析構方法')  # 對象被銷毀時,自動執行

obj = foo()   # 自動執行__init__方法(python自己規定的)
obj()  # 自動執行__call__方法 (python自己規定的)
foo()()
           
out:
	init
	析構方法
	call
	init
	call
	析構方法
           
def __int__():  int(對象)
def __str__():  str()
def __init__():
def __call__():
__dict__  # 将對象中封裝的所有内容通過字典的形式傳回
           
class foo:
    def __init__(self,name,age,sex):
        self.name = name
        self.age = age
        self.sex = sex

obj = foo('fengye',12,'male')
str = obj.__dict__
print(str)
           
out:
	{'name': 'fengye', 'age': 12, 'sex': 'male'}
           
class Foo:

    def __init__(self):
        pass

    def __getitem__(self, item):
        return item+10

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

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

li = Foo()
r = li[8]
print(r)

li[100] = 'asad'
del li[999]
           
out:
	18
	100 asad
	999