Magic properties in Python

HUIDBK 2021-04-06 14:33:13
magic properties python

Python Magic attributes in

Magic attribute

stay Python in , All with __ The method of wrapping double underscores , They are collectively called Magic Method, For example, class initialization methods __init__() , Instance object creation method __new__() etc. .

The magic properties and methods are Python Some of the built-in properties and methods , It has a special meaning . Two underscores before and after naming , When performing system specific operations , Automatically called .

Common magic properties


Represents the description information of the class

# __doc__
class Foo:
    """  Description class information , This is the class for testing  """
    def func(self):

# ipython  test
In [2]: Foo.__doc__
Out[2]: '  Description class information , This is the class for testing  '

__module__ and __class__

  • __module__ The object representing the current operation is in that module
  • __class__ What is the class representing the object being operated on

# __module__、__class__
class Student(object):
    def __init__(self, name): = name
from oop import Student

s = Student()
print(s.__module__)  #  Output  oop  namely : output module
print(s.__class__)   #  Output  <class 'oop.Student'>  namely : Output class

__init__ 、__new__

__init__() Initialization method and __new__(), When an object is created through a class , Automatic trigger execution .__new__ Is used to create a class and return an instance of that class , and __init__ Just initialize the instance with the passed in parameters .

  • __new__() Called when an object is created , Will return an instance of the current object

  • __init__() After the object is created, it is called , Initialize some instances of the current object , No return value

# __init__ 、 __new__
class Student(object):

    def __init__(self, name, age):
        print('__init__() called') = name
        self.age = age

    def __new__(cls, *args, **kwargs):
        print('__new__() called')
        print(cls, args, kwargs)
        return super().__new__(cls)

# ipython  test
In [26]: s1 = Student('hui', age=21)
__new__() called
<class '__main__.Student'> ('hui',) {'age': 21}
__init__() called

In [27]: s2 = Student('jack', age=20)
__new__() called
<class '__main__.Student'> ('jack',) {'age': 20}
__init__() called


When an object is freed in memory , Automatic trigger execution .

notes : This method is generally not defined , because Python It's a high-level language , Yes memory management 、 Garbage collection mechanism , Programmers do not have to worry about the allocation and release of memory when using it , Because the job is given Python The interpreter executes , therefore ,__del__ Is automatically triggered by the interpreter during garbage collection .

# __del__
class Foo:
    def __del__(self):
        print('__del__() called')

# ipython  test
In [29]: f = Foo()

In [30]: del f
__del__() called


Let instances of classes behave like functions , You can call them , Pass a function as a parameter to another function, etc . It's a very powerful feature , It gives way Python Programming is more comfortable and sweet . The object is followed by parentheses , Trigger execution .

notes :__init__ The execution of the method is triggered by the creation of the object , namely : object = Class name () ; And for __call__ Method execution is triggered by an object followed by a parenthesis , namely : object () perhaps class ()()

__call__ In those Class instances can be very effective when they change state frequently . Calling this instance is a direct and elegant way to change the state of the object . It's best to express it with an example :

# __call__
class Rect(object)
     Call the instance object to change the position of the rectangle

    def __init__(self, x, y):

        # x, y Represents rectangular coordinates
        self.x, self.y = x, y

    def __call__(self, x, y):        
        #  Change the position of the entity
        self.x, self.y = x, y

# ipython  test
In [33]: r = Rect(1010)

In [34]: r.x, r.y
Out[34]: (1010)

In [35]: r(00)

In [36]: r.x, r.y
Out[36]: (00)

In [37]: r(100100)

In [38]: r.x, r.y
Out[38]: (100100)


All properties in a class or object

The instance property of the class belongs to the object ; Class properties and methods in a class belong to a class , namely :

# __dict__
class Student(object):

    def __init__(self, name, age): = name
        self._age = age

    def age(self):
        return self._age

# ipython  test
In [47]: #  Get class properties

In [48]: Student.__dict__
              '__init__': <function __main__.Student.__init__(self, name, age)>,
              'age': <property at 0x210e2a005e8>,
              '__dict__': <attribute '__dict__' of 'Student' objects>,
              '__weakref__': <attribute '__weakref__' of 'Student' objects>,

In [49]: #  Get the properties of the instance object

In [50]: s = Student('hui'21)

In [51]: s.__dict__
Out[51]: {'name''hui''_age'21}

In [52]: s2 = Student('jack'20)

In [53]: s2.__dict__
Out[53]: {'name''jack''_age'20}


If a class is defined __str__ Method , So in print object when , The default output is the return value of the method .

In [65]: # __str__
    ...: class Foo(object):
    ...:     pass

In [66]: f = Foo()

In [67]: print(f)
<__main__.Foo object at 0x00000210E2715608>

In [68]: class Foo(object):
    ...:     def __str__(self):
    ...:         return '< Custom Foo object str >'

In [69]: f = Foo()

In [70]: print(f)
< Custom Foo object str >


For index operation , Such as a dictionary . The above are respectively for obtaining 、 Set up 、 Delete data .

For slicing operations , As listing .

Dictionary example

# __getitem__、__setitem__、__delitem__
class MyDict(object):

    def __init__(self):
        self.my_dict = dict()

    def __getitem__(self, key):
        print('__getitem__() ', key)
        return self.my_dict.get(key, None)

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

    def __delitem__(self, key):
        print('__delitem__() ', key)
        del self.my_dict[key]

# ipython  test         
In [33]: mdict = MyDict()

In [34]: print(mdict['name'])
__getitem__()  name

In [35]: #  newly added

In [36]: mdict['name'] = 'hui'
__setitem__()  name hui

In [37]: mdict['age'] = 21
__setitem__()  age 21

In [38]: mdict['name']
__getitem__()  name
Out[38]: 'hui'

In [39]: mdict['age']
__getitem__()  age
Out[39]: 21

In [40]: #  to update

In [41]: mdict['name'] = 'jack'
__setitem__()  name jack

In [42]: mdict['name']
__getitem__()  name
Out[42]: 'jack'

In [43]: #  Delete

In [44]: del mdict['age']
__delitem__()  age

In [45]: print(mdict['age'])
__getitem__()  age

List example

#  Slicing operation 
class MyList(object):

    def __init__(self):
        self.mlist = list()

    def __getitem__(self, index):
        print('__getitem__() called')
        if isinstance(index, slice):
            return self.mlist[index]

    def __setitem__(self, index, value):
        print('__getitem__() called')
        print(index, value)
        if isinstance(index, slice):
            self.mlist[index] = value

    def __delitem__(self, index):
        print('__delitem__() called')
        if isinstance(index, slice):
            del self.mlist[index]
# ipython  test
In [70]: mlist = MyList()

In [71]: mlist[0]
__getitem__() called

In [72]: mlist[0:-1]
__getitem__() called
Out[72]: []

In [73]: mlist[:] = [1,2,3]
__getitem__() called
slice(NoneNoneNone) [123]

In [74]: mlist[:]
__getitem__() called
Out[74]: [123]

In [75]: mlist[0:2]
__getitem__() called
Out[75]: [12]

In [76]: mlist[::-1]
__getitem__() called
Out[76]: [321]

In [77]: mlist[0]
__getitem__() called

In [78]: mlist[0:1]
__getitem__() called
Out[78]: [1]

In [79]: del mlist[0:1]
__delitem__() called

In [80]: mlist[:]
__getitem__() called
Out[80]: [23]

Be careful : When doing mlist[0] When operating, delivery is not a slice object , Is not a int Type of number , So you can't index it as 0 Take out the value of , Change to mlist[0, 1] Or in __getitem__() New number judgment is added in the method of , You can try .


with The statement is from Python2.5 The key words we started to introduce . You should have met code like this :

with open('foo.txt'as bar:
    # do something with bar

stay with In the declared code snippet , We can start and exit some objects , It can also handle exceptions . This requires two magic methods : __enter__ and __exit__.


Defined when using with At the time of statement , The behavior of the session manager when the block is initially created . Please note that ,__enter__ The return value of is the same as with The target of the statement or as After the name binding .

__exit__(self, exception_type, exception_value, traceback):

Defines when a block of code is executed or terminated , What session manager should do . It can be used to handle exceptions 、 Do some cleaning work or do some routine work after the code block is executed . If the code block executes successfully ,exception_type,exception_value, and traceback Will be None . otherwise , You can choose to handle the exception or just leave it to the user . If you want to handle this exception , Please make sure __exit__ Returns after all statements True. If you want exceptions to be handled by the session manager , Then let it produce the exception .


occasionally , Especially when you're dealing with mutable objects , You may want to copy an object , Then make some changes to it without affecting the original object . This is it. Python Of copy Where it works .


Defines when calling to an instance of your class copy.copy() The behavior that happens when you're in the middle of something .copy.copy() Returns a shallow copy of your object —— It means , When the instance itself is a new instance , All of its data is referenced —— for example , When an object itself is copied , Its data is still referenced ( therefore , Changes to the data in the shallow copy may still result in changes to the data in the original object ).

__deepcopy__(self, memodict={}):

Defines when calling to an instance of your class copy.deepcopy() The behavior that happens when you're in the middle of something .copy.deepcopy() Returns a deep copy of your object —— The object and its data are copied .memodict Is a cache of previously copied objects —— This optimizes the copy process and prevents infinite recursion when copying recursive data structures . When you want to make a deep copy of a single property , call copy.deepcopy(), And memodict For the first parameter .

The use cases of these magic methods look small , And it's really practical . They reflect something important about object-oriented programs in Python On , And on the whole Python There's always an easy way to find something , Even if it's not necessary . These magic methods may not seem very useful , But once you need them , You'll be glad they exist .

Other magic methods

Because of the magical properties 、 There are too many methods to describe and show one by one here , The rest is presented in tabular form .

The magic of comparison

Method effect
__cmp__(self, other) Comparison method is the most basic magic method
__eq__(self, other) The act of defining equality symbols ,==
__ne__(self,other) Defining the behavior of unequal symbols ,!=
__lt__(self,other) Define behaviors that are less than symbols ,<
__gt__(self,other) Define behaviors larger than symbols ,>
__le__(self,other) Define the behavior of a symbol less than or equal to ,<=
__ge__(self,other) Define the behavior of symbols greater than or equal to ,>=

Magic method of numerical calculation

Monocular operators and functions

Method effect
__pos__(self) Implementation of a positive number of operations
__neg__(self) Implementation of a negative number of operations
__abs__(self) Implement a built-in abs() Behavior of functions
__invert__(self) Implement a negation operator (~ The operator ) act
__round__(self, n) Implement a built-in round() Behavior of functions
__floor__(self) Realization math.floor() The functional behavior of
__ceil__(self) Realization math.ceil() The functional behavior of
__trunc__(self) Realization math.trunc() The functional behavior of

Binocular operators or functions

Method effect
__add__(self, other) Implement an addition
__sub__(self, other) Implement a subtraction
__mul__(self, other) Implement a multiplication
__floordiv__(self, other) Achieve one // The integer division operation produced by the operator
__div__(self, other) Achieve one / The division operation represented by the operator
__truediv__(self, other) Implement real division
__mod__(self, other) Achieve one % The modular operation represented by the operator
__divmod__(self, other) Implement a built-in function divmod()
__pow__(self, other) Implement an exponential operation ( ****** The operator ) act
__lshift__(self, other) Implement a bit shift left operation **(<<)** The function of
__rshift__(self, other) Implement a bit shift right operation **(>>)** The function of
__and__(self, other) Implementation of a bit by bit and operation **(&)** act
__or__(self, other) The act of implementing a bitwise process or operation
__xor__(self, other) The XOR operator is equivalent to ^

Incremental operations

Method effect
__iadd__(self, other) Addition assignment
__isub__(self, other) Subtraction assignment
__imul__(self, other) Multiplication assignment
__ifloordiv__(self, other) Division assignment , Floor removal , amount to //= Operator
__idiv__(self, other) division assignment , amount to /= Operator
__itruediv__(self, other) True division assignment
__imod_(self, other) Module assignment , amount to %= Operator
__ipow__(self, other) Power assignment , amount to **= Operator
__ilshift__(self, other) Shift left assignment , amount to <<= Operator
__irshift__(self, other) Shift left assignment , amount to >>= Operator
__iand__(self, other) And assignment , amount to &= Operator
__ior__(self, other) Or assignment
__ixor__(self, other) Exclusive or operator , amount to ^= Operator

Type conversion

Method effect
__int__(self) Convert to integer
__long__(self) Transform growth and shape
__float__(self) Convert to floating point
__complex__(self) convert to Plural
__oct__(self) Convert to octal
__hex__(self) Convert to hex
__index__(self) If you define a numeric type that might be used for slicing , You should define __index__
__trunc__(self) When math.trunc(self) Called when using __trunc__ Returns an integer truncation of its own type
__coerce__(self, other) Perform mixed type operations

official account

New folder X

It took nature tens of billions of years to create our real world , And programmers use hundreds of years to create a completely different virtual world . We use the keyboard to make bricks and tiles , Build everything with your brain . People put 1000 Regard as authority , We do the opposite , defend 1024 The status of . We're not keyman , We are just the extraordinary creators of the ordinary world .


  1. Docker | 多图预警 | 配置Docker下Python开发环境
  2. Docker | multi graph warning | configuring Python development environment under docker
  3. 课程学习记录之python迭代器和生成器
  4. Python_学习之流程控制
  5. Python_学习之运算符
  6. Python_学习之基础数据类型
  7. Python_学习之虚拟环境的搭建
  8. Python iterator and generator of course learning record
  9. Python_ Process control of learning
  10. Python_ Learning operators
  11. Python_ Basic data types of learning
  12. Python_ The construction of virtual learning environment
  13. 一个非常简单好用的 Python 图形界面库
  14. 我就是这样学 Python 的
  15. 零基础,从一个抢票程序,提升自己的Python技能
  16. A very simple and easy to use Python graphical interface library
  17. That's how I learned python
  18. 商业数据分析从入门到入职(9)Python网络数据获取
  19. Zero basis, improve your Python skills from a ticket grabbing program
  20. 商业数据分析从入门到入职(8)Python模块、文件IO和面向对象
  21. 商业数据分析从入门到入职(7)Python基础数据结构及其操作
  22. 商业数据分析从入门到入职(6)Python程序结构和函数
  23. Business data analysis from entry to entry (9) Python Network Data Acquisition
  24. Business data analysis from entry to entry (8) Python module, file IO and object oriented
  25. Business data analysis from entry to entry (7) Python basic data structure and its operation
  26. Business data analysis from entry to entry (6) Python program structure and function
  27. 简简单单实现 Python Web 的登录注册页面,还包含一半逻辑。
  28. Simple implementation of Python web login registration page, but also contains half of the logic.
  29. 什么是pip?Python新手入门指南
  30. What is PIP? Getting started with Python
  31. Python uses for... Else to jump out of double nested loop
  32. Python基础之:Python中的内部对象
  33. 人工智能入门:Python实现机器学习
  34. The foundation of Python: inner objects in Python
  35. Introduction to artificial intelligence: machine learning in Python
  36. Python基础之:Python中的内部对象
  37. The foundation of Python: inner objects in Python
  38. Python 小技之 Office 文件转 PDF
  39. 还在为多张Excel汇总统计发愁?Python 秒处理真香!
  40. 用 Python 制作音乐聚合下载器
  41. Spark Delta Lake 0.4.0 发布,支持 Python API 和部分 SQL
  42. How to transfer office files to PDF
  43. Are you still worried about multiple excel summary statistics? Python second processing really fragrant!
  44. Making music aggregate downloader with Python
  45. Spark delta Lake 0.4.0 is released, supporting Python API and part of SQL
  46. Python信息搜集
  47. Python information gathering
  48. Python - 关于类(self/cls) 以及 多进程通讯的思考
  49. Python - thinking about class (self / CLS) and multi process communication
  50. Python - 关于类(self/cls) 以及 多进程通讯的思考
  51. Python - thinking about class (self / CLS) and multi process communication
  52. Python信用评分卡建模(附代码)
  53. Python credit score card modeling (with code)
  54. 学Python需要学数据库吗?Python学习教程!
  55. Do you need to learn database to learn Python!
  56. Python私有变量如何定义?Python学习教程!
  57. How to define Python private variables? Python tutorial!
  58. Python数据分析入门(六):Pandas的函数应用
  59. Introduction to Python data analysis (6): function application of pandas
  60. 学Python需要学数据库吗?Python学习教程!