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
  1. class Zarten():

  2. def __repr__(self):

  3. return 'my name is Zarten_1'

  4. \

  5. def __str__(self):

  6. return 'my name is Zarten_2'

  7. \

  8. z = Zarten()

  9. print(z)

Copy the code
  1. my name is Zarten_2
  • __iter__()

\

Returns an iterable, usually used \ with __next__()

Copy the code
  1. class Zarten():

  2. def __init__(self, brother_num):

  3. self.brother_num = brother_num

  4. self.count = 0

  5. \

  6. def __iter__(self):

  7. return self

  8. \

  9. def __next__(self):

  10. if self.count >= self.brother_num:

  11. raise StopIteration

  12. else:

  13. self.count += 1

  14. return 'zarten_' + str(self.count)

  15. \

  16. \

  17. zarten = Zarten(5)

  18. for i in zarten:

  19. 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
  1. class Zarten():

  2. def __init__(self):

  3. self.brother = ['zarten_1','zarten_2','zarten_3','zarten_4','zarten_5',]

  4. \

  5. def __getitem__(self, item):

  6. return self.brother[item]

  7. \

  8. zarten = Zarten()

  9. print(zarten[2])

  10. print(zarten[1:3])

  11. \

  12. for i in zarten:

  13. 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
  1. class Zarten():

  2. def __new__(cls, *args, **kwargs):

  3. print('__new__')

  4. return super().__new__(cls)

  5. \

  6. def __init__(self, name, age):

  7. print('__init__')

  8. self.name = name

  9. self.age = age

  10. \

  11. def __repr__(self):

  12. return 'name: %s age:%d' % (self.name,self.age)

  13. \

  14. zarten = Zarten('zarten', 18)

  15. print(zarten)

Copy the code
  1. __new__
  2. __init__
  3. name:zarten age:18

Use __new__() to implement the singleton pattern

Copy the code
  1. class Zarten():

  2. _singleton = None

  3. \

  4. def __new__(cls, *args, **kwargs):

  5. print('__new__')

  6. if not cls._singleton:

  7. cls._singleton = super().__new__(cls)

  8. return cls._singleton

  9. \

  10. def __init__(self, name, age):

  11. print('__init__')

  12. self.name = name

  13. self.age = age

  14. \

  15. def __repr__(self):

  16. return 'name: %s age:%d' % (self.name,self.age)

  17. \

  18. zarten = Zarten('zarten', 18)

  19. zarten_1 = Zarten('zarten_1', 19)

  20. print(zarten)

  21. print(zarten_1)

  22. print(zarten_1 == zarten)

Copy the code
  1. __new__
  2. __init__
  3. __new__
  4. __init__
  5. name:zarten_1 age:19
  6. name:zarten_1 age:19
  7. 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
  1. class Zarten():

  2. \

  3. def __init__(self, name, age):

  4. self.name = name

  5. self.age = age

  6. \

  7. def __call__(self):

  8. print('name:%s age:%d' % (self.name, self.age))

  9. \

  10. \

  11. z = Zarten('zarten', 18)

  12. print(callable(z))

  13. 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
  1. class Zarten():

  2. \

  3. def __init__(self, file_name, method):

  4. self.file_obj = open(file_name, method)

  5. \

  6. def __enter__(self):

  7. return self.file_obj

  8. \

  9. def __exit__(self, exc_type, exc_val, exc_tb):

  10. self.file_obj.close()

  11. print('closed')

  12. \

  13. \

  14. with Zarten('e:\\test.txt', 'r') as f:

  15. r = f.read()

  16. 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
  1. class Zarten():

  2. \

  3. def __init__(self, age):

  4. self.age = age

  5. \

  6. def __add__(self, other):

  7. return self.age + other

  8. \

  9. def __radd__(self, other):

  10. return self.age + other

  11. \

  12. \

  13. \

  14. z = Zarten(18)

  15. print(z + 10)

  16. print(20 + z)

  • __del__() 

\

Called at the end of an object’s life cycle, equivalent to a destructor

\

Copy the code
  1. class Zarten():

  2. \

  3. def __init__(self, age):

  4. self.age = age

  5. \

  6. def __del__(self):

  7. print('__del__')

  8. \

  9. \

  10. 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” **