类的特殊方法

__init__()   实例化后,赋值的时候执行

 

__new__()       实例化时执行   
1 # 4.__new__方法 2 # 单例模式:是一种设计模式 3 class Singleton: 4 def __new__(cls, *args, **kw): 5 if not hasattr(cls, '_instance'): 6 orig = super(Singleton, cls) 7 cls._instance = orig.__new__(cls, *args, **kw) 8 return cls._instance 9 10 one = Singleton() 11 two = Singleton() 12 print(one,two) #他们两个的地址一样 13 14 one.name = 'alex' 15 print(two.name)
__call__()        实例化对象()  执行该方法

1 class Foo:
2     def __call__(self, *args, **kwargs):
3         print(123)
4 # f = Foo()
5 # f() #如果不写上面的__call__方法,就不会调用。如果加上,就正确了
6 Foo()() #也可以这样表示
__getattr__()       #找不到属性时,会走此方法    和getattr()无关
1 >>> class test():
 2 ...     name="xiaohua"
 3 ...     def run(self):
 4 ...             return "HelloWord"
 5 ...
 6 >>> t=test()
 7 >>> getattr(t, "name") #获取name属性,存在就打印出来。
 8 'xiaohua'
 9 >>> getattr(t, "run")  #获取run方法,存在就打印出方法的内存地址。
10 <bound method test.run of <__main__.test instance at 0x0269C878>>
11 >>> getattr(t, "run")()  #获取run方法,后面加括号可以将这个方法运行。
12 'HelloWord'
13 >>> getattr(t, "age")  #获取一个不存在的属性。
14 Traceback (most recent call last):
15   File "<stdin>", line 1, in <module>
16 AttributeError: test instance has no attribute 'age'
17 >>> getattr(t, "age","18")  #若属性不存在,返回一个默认值。
18 '18'
19 >>>

 

1 >>> class test():
 2 ...     name="xiaohua"
 3 ...     def run(self):
 4 ...             return "HelloWord"
 5 ...
 6 >>> t=test()
 7 >>> hasattr(t, "age")   #判断属性是否存在
 8 False
 9 >>> setattr(t, "age", "18")   #为属相赋值,并没有返回值
10 >>> hasattr(t, "age")    #属性存在了
11 True
12 >>>
1 >>> class test():
 2 ...     name="xiaohua"
 3 ...     def run(self):
 4 ...             return "HelloWord"
 5 ...
 6 >>> t=test()
 7 >>> hasattr(t, "name") #判断对象有name属性
 8 True
 9 >>> hasattr(t, "run")  #判断对象有run方法
10 True
11 >>>

 

__getattribute__()   #属性拦截器
__getitem__()   

1 class Foo:
 2     def __init__(self):
 3         self.name = 'egon'
 4         self.age = 73
 5         self.l=[1,2,3]
 6     def __getitem__(self, item):  #得到
 7         # return  self.l[item]
 8         # return self.__dict__[item]
 9         # print(Foo.__dict__)
10         return 123
11     def __setitem__(self, key, value):  #修改
12         print(key,value)
13         self.__dict__[key] = value
14     def __delitem__(self, key):  #删除
15         del self.__dict__[key]
16 f = Foo()
17 print(f['qqq'])  #不管里面放的啥值,它都会得到返回值的内容,调用的是__getitem__方法
18 f['name']='alex' #修改egon的值为alex,调用 __setitem__方法
19 # del f['name'] #删除name,就会报错了,说明在调用__delitem__方法调用成功了,就已经删了,就会报错了
20 print(f.name) 
21 f1 = Foo()
22 print(f == f1)
23 # print(f.name)
24 # print(f[0])  #一开始不能这样取值,但是提供了一个__getitem__方法,这样就可以用了
25 # print(f[1])
26 # print(f[2])
__del__()   #当对象在内存被释放时,自动触发执行
__eq__()
1 class A:
2     def __eq__(self, other):
3         return True
4 a = A()
5 b = A()
6 print(a==b) #不加方法的时候返回的是False,加了个__eq__方法就返回了个True
7 # '=='内部就调用了__eq__方法
8 print(a is b)

 

posted @ 2019-01-06 18:21  团子emma  阅读(108)  评论(0)    收藏  举报