Object oriented 7.8: Method A double
Definition: The Double Down is a special method we try not to double-down method used in the development.
7.8.1 __len__
class B:
def __len__(self): # 必须有一个int类型的返回值 否则会报错,但仍会执行此方法
print(999)
return 666
b = B()
print(len(b)) # len 一个对象就会触发 __len__方法
class A:
def __init__(self):
self.name = 'Agoni'
self.age = 18
def __len__(self):
return len(self.__dict__) # 返回的是a 对象的全部内容的长度
a = A()
print(len(a))
# 一个对象之所以可以使用len()函数,根本原因是这个对象从属于的类中有__len__方法
7.8.2 __hash__
class A:
def __init__(self):
self.a = 1
self.b = 2
def __hash__(self):
return hash(str(self.a)+str(self.b))
obj = A()
print(hash(obj)) # 会调用obj这个对象的类(基类)的__hash__方法
7.8.3 __str__
, __repr__
If a class is defined in the __str__或__repr__
method, then when the print target, the default output the return value
class Student:
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self): # 优先级要高
return f'姓名:{self.name},年龄:{self.age}'
def __repr__(self):
return f'姓名:{self.name},年龄:{self.age}'
obj1 = Student('a',18)
obj2 = Student('b',18)
print(str(obj1)) # 会触发 __str__
print(str(obj2)) # 会触发 __repr__
print(obj1)
print(obj2) # 打印输出实例会出发__str__ 和 __repr__
print('此对象为%s' % obj1) # 格式化输出会触发__str__
print('此对象为%r' % obj2) # 格式化输出会触发__str__
7.8.4 __call__
Brackets behind the object, trigger the execution.
NOTE: constructor __new__
execution is triggered by the objects created, namely: class name = Object (); For the __call__
method performed by the bracketed object triggers, namely: Object () or class () ()
class A:
def __init__(self):
self.a = 1
print(111)
def __call__(self, *args, **kwargs):
print(666)
obj = A()
obj()
7.8.5 __eq__
Two classes of objects a compare operation triggers __eq__
method
class A:
def __init__(self):
self.a = 1
self.b = 2
def __eq__(self,obj):
print(111)
return True
# if self.a == obj.a and self.b == obj.b:
# return True
a = A()
b = A()
print(a == b)
7.8.6 __del__
Destructor, when the object is released in the memory, automatically trigger the execution.
Note: This method is generally no need to define, because Python is a high-level language, programmers used without concern allocate and free memory, because this work is to the Python interpreter to execute, so call the destructor is It triggered automatically performed at the time garbage collector by an interpreter.
class A:
def __del__(self):
print(111)
obj = A()
del obj # 打印111
l1 = [1,2,3]
dic = {1:2}
del l1
del dic # 主动删除
print(dic) # 会报错
print(111)
print(222)
7.8.7 __new__
***
__new__
Constructor: __new__
create a new object and returns
class A(object):
def __init__(self):
print('in __init__')
# 这里的__new__不能创造空间,必须引用父类的__new__创造空间
def __new__(cls, *args, **kwargs): # 传一个类给cls,确定给哪个类创建空间
print('in __new__')
object1 = object.__new__(cls)
return object1
obj = A() # 类名() 先触发__new__ 并且将类名自动传给cls
print(obj)
Singleton - a design pattern (interview handwriting singleton)
A class can instantiate an object, no matter how many times you instantiate, have only one object in memory
The object is not personalized this class, mainly after instantiating the object to perform the methods in the class
class A:
__instance = None
def __new__(cls,*args.**kwargs):
if not __instance:
object1 = object.__new__(cls)
cls.__instance = object1
return cls.__instance
obj1 = A()
obj2 = A()
print(obj1,obj2) # 两个对象空间相同
7.8.8 __item__
Use the operation is similar to the object dictionary
class Foo:
def __init__(self,name):
self.name = name
def __getitem__(self, item):
print(self.__dict__[item]) # 得到Agoni
print(item) # name
print('get时,执行我')
def __setitem__(self, key, value):
self.__dict__[key] = value # 才是更改 __init__ 的属性name
print(key,value) # name 小姐姐
print('set时,执行我')
def __delitem__(self, key):
print(f'del obj{[key]}时,我执行')
self.__dict__.pop(key)
obj = Foo('Agoni')
obj['name'] # 将 name 传给 item
obj['name'] = '小姐姐' # 将 name 和 小姐姐 传给 key 和 value , __init__ 的属性name
print(obj.name) # 小姐姐
del obj['name']
7.8.9 __enter__
__exit__
class A:
def __init__(self,name):
self.name = name
def __enter__(self):
print('开始')
def __exit__(self, exc_type, exc_val, exc_tb):
print('结束')
# 对一个对象类似于进行with语句上下文管理的操作,必须在类中定义__enter__ 和__exit__
with A('Agoni') as obj:
print(666)
print(obj.name) # 这里会报错(看下面例子,会解决)
开始
666
结束
# 举例
class A:
def __init__(self, text):
self.text = text
def __enter__(self): # 开启上下文管理器对象时触发此方法
self.text = self.text + '您来啦'来了来了
return self # 将实例化的对象返回f1
def __exit__(self, exc_type, exc_val, exc_tb): # 执行完上下文管理器对象f1时触发此方法
self.text = self.text + '这就走啦'
with A('大爷') as f1:
print(f1.text)
print(f1.text)