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. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database