Illustrations by Nikita Pilyukshin
♚
Zarten, a front-line Internet worker.
Blog: zhihu.com/people/zarten
\
An overview of the
Special python methods (magic methods) are called by the Python interpreter. We don’t need to call them ourselves. We use built-in functions to use them. For example, when the special __len__() method is implemented, we simply use len(); Some special methods are called implicitly, for example: for I in x: the built-in iter(x) function is used behind it.
Some common ad-hoc methods and implementations are described below. By implementing a class
Commonly used special methods and implementation
- __len__()
Generally returns the number, called with len(). The len() function \ can also be used inside __len__()
class Zarten(): def __init__(self, age): self.age = age self.brother = ['zarten_1', 'zarten_2'] def __len__(self): Return len(self.brother) # len() # return self.age z = Zarten(18) print(len(z))Copy the code
- __str__()
\
The string representation of an object is basically the same as __repr__(), with minor differences:
__str__() is for end users, and __repr__() is for developers, for debugging, logging, etc.
2. On the command line, after implementing __str_(), directly entering the object name will display the object memory address; ‘repr(), on the other hand, has the same effect as print (object).
3. If both are implemented, __str_() is called, and __repr__() is generally implemented in the class at least.
Copy the code
-
class Zarten():
-
def __repr__(self):
-
return 'my name is Zarten_1'
-
\
-
def __str__(self):
-
return 'my name is Zarten_2'
-
\
-
z = Zarten()
-
print(z)
Copy the code
my name is Zarten_2
- __iter__()
\
Returns an iterable, usually used \ with __next__()
Copy the code
-
class Zarten():
-
def __init__(self, brother_num):
-
self.brother_num = brother_num
-
self.count = 0
-
\
-
def __iter__(self):
-
return self
-
\
-
def __next__(self):
-
if self.count >= self.brother_num:
-
raise StopIteration
-
else:
-
self.count += 1
-
return 'zarten_' + str(self.count)
-
\
-
\
-
zarten = Zarten(5)
-
for i in zarten:
-
print(i)
- __getitem__()
\
This special method returns data and can also replace the __iter_() and __next__() methods, as well as support slicing
Copy the code
-
class Zarten():
-
def __init__(self):
-
self.brother = ['zarten_1','zarten_2','zarten_3','zarten_4','zarten_5',]
-
\
-
def __getitem__(self, item):
-
return self.brother[item]
-
\
-
zarten = Zarten()
-
print(zarten[2])
-
print(zarten[1:3])
-
\
-
for i in zarten:
-
print(i)
- __new__()
\
__new__() is used to construct an instance of a class. The first argument is CLS, which is not normally used. __init__() is used to initialize the instance, so __new__() is executed before __init___().
If __new__() does not return, no object is created and __init___() is not executed;
If __new__() returns an instance of another class, __init___() will not execute either;
Purpose: Use __new___() to implement the singleton pattern
Copy the code
-
class Zarten():
-
def __new__(cls, *args, **kwargs):
-
print('__new__')
-
return super().__new__(cls)
-
\
-
def __init__(self, name, age):
-
print('__init__')
-
self.name = name
-
self.age = age
-
\
-
def __repr__(self):
-
return 'name: %s age:%d' % (self.name,self.age)
-
\
-
zarten = Zarten('zarten', 18)
-
print(zarten)
Copy the code
__new__
__init__
name:zarten age:18
Use __new__() to implement the singleton pattern
Copy the code
-
class Zarten():
-
_singleton = None
-
\
-
def __new__(cls, *args, **kwargs):
-
print('__new__')
-
if not cls._singleton:
-
cls._singleton = super().__new__(cls)
-
return cls._singleton
-
\
-
def __init__(self, name, age):
-
print('__init__')
-
self.name = name
-
self.age = age
-
\
-
def __repr__(self):
-
return 'name: %s age:%d' % (self.name,self.age)
-
\
-
zarten = Zarten('zarten', 18)
-
zarten_1 = Zarten('zarten_1', 19)
-
print(zarten)
-
print(zarten_1)
-
print(zarten_1 == zarten)
Copy the code
__new__
__init__
__new__
__init__
name:zarten_1 age:19
name:zarten_1 age:19
True
- __call__()
\
This object can be called like a function. For example, custom functions, built-in functions, and classes are all callable objects. Callable () can be used to determine whether they are callable objects
Copy the code
-
class Zarten():
-
\
-
def __init__(self, name, age):
-
self.name = name
-
self.age = age
-
\
-
def __call__(self):
-
print('name:%s age:%d' % (self.name, self.age))
-
\
-
\
-
z = Zarten('zarten', 18)
-
print(callable(z))
-
z()
- __enter__()
\
A context manager class must implement these two special methods: __enter_() and __exit__(), which are called using the with statement.
Use __enter__() to return the object and __exit__() to close the object
Copy the code
-
class Zarten():
-
\
-
def __init__(self, file_name, method):
-
self.file_obj = open(file_name, method)
-
\
-
def __enter__(self):
-
return self.file_obj
-
\
-
def __exit__(self, exc_type, exc_val, exc_tb):
-
self.file_obj.close()
-
print('closed')
-
\
-
\
-
with Zarten('e:\\test.txt', 'r') as f:
-
r = f.read()
-
print(r)
- __add__()
\
Addition operator overloading and __radd__() reverse operator overloading
When object as additive, the first will be “+” on the left side of the object to find __add__ (), if can’t find it in the “+” on the right side of the search __radd__ ()
Copy the code
-
class Zarten():
-
\
-
def __init__(self, age):
-
self.age = age
-
\
-
def __add__(self, other):
-
return self.age + other
-
\
-
def __radd__(self, other):
-
return self.age + other
-
\
-
\
-
\
-
z = Zarten(18)
-
print(z + 10)
-
print(20 + z)
- __del__()
\
Called at the end of an object’s life cycle, equivalent to a destructor
\
Copy the code
-
class Zarten():
-
\
-
def __init__(self, age):
-
self.age = age
-
\
-
def __del__(self):
-
print('__del__')
-
\
-
\
-
z = Zarten(18)
Summary of special (magic) methods
\
Hot recommended in Python create WeChat robot in Python robot to monitor WeChat group chat in Python for cameras and real-time control face open source project | beautification LeetCode warehouse is recommended in Python Python Chinese community’s several kind of public service, announced notice | Python Chinese Community award for articles \
Click to become a registered member of the community ** “Watching” **