Python Advanced (13) – Get special attributes of object information

Original link: https://chegva.com/5288.html

◎Knowledge points

  1. Special properties and special methods

  2. Special attribute __dict__

  3. Special attribute __doc__

  4. Special attribute __slots__

◎Script practice

Special properties and special methods

 """One, special properties and special methods"""  """ In the return value after calling the built-in function dir(), many attributes and methods start and end with double underscores __, and most of these attributes and methods are inherited from the class object """  print(dir(object))  """ Properties that begin and end with a double underscore __ are called special properties, and methods that begin and end with a double underscore __ are called special methods. Special attributes and special methods are predefined by the system, and our custom attribute names and method names should not start and end with double underscores __. When we customize class objects, we often override one or more special methods, such as __init__. Special methods are called automatically in certain situations, and it is rarely necessary to manually call special methods""" 

Special attribute __dict__

 """Second, special attributes __dict__"""  """ For a specified class object or instance object, you can access the special attribute __dict__ to get a dictionary of all attributes and methods bound to the class object or instance object. Among them, the key in the dictionary is the attribute name or method name """  class MyClass(object): ca = "ca"  def __init__(self): self.ia = "ia"  def im(self): pass  @classmethod def cm(cls): pass  @staticmethod def sm(): pass  MyClass.ca2 = "ca2" print(MyClass.__dict__)  mc = MyClass() mc.ia2 = "ia2" print(mc.__dict__) # {'ia': 'ia', 'ia2': 'ia2'} 

Special attribute __doc__

 """Three, special attributes __doc__"""  """ Among all the attributes of the class object obtained by calling the built-in function dir, there is a special attribute called __doc__, which is used to represent the docstring of the class object. 1. What is the docstring of the class object? Similar to the docstring of a function, the string on the first line of a class object is called the docstring of the class object, usually denoted by three quotation marks The docstring of a class object is a brief description of the function of the class object  In PyCharm, docstrings for class objects are grayed out  It's called a "doc" string because tools can be used to automatically generate documentation from docstrings  You should get into the habit of writing docstrings to improve program readability"""  class MyClass(object): """This is the docstring for the class object""" pass  """ 2. Accessing the docstring of the class object The docstring of the class object can be accessed through the special attribute __doc__ of the class object. The help information obtained by calling the built-in function help() will contain the docstring of the class object """  print(list.__doc__) print(MyClass.__doc__) # This is the docstring of the class object print(help(list)) print(help(MyClass)) 

Special attribute __slots__

 """Four. Special attribute __slots__"""  """ Python is a dynamic language, so after creating an object, you can dynamically bind attributes and methods to it. If you want to restrict the names of the attributes and methods dynamically bound to an instance object, you can define a special class object in its corresponding class object. attribute __slots__, and assign __slots__ a list or tuple whose elements are all strings, In this way, the names of properties and methods dynamically bound to instance objects can only come from the element """ in __slots__  class MyClass(object): __slots__ = ("attr1", "do_sth1")  mc = MyClass()  mc.attr1 = 18  # mc.attr2 = 56 # AttributeError: 'MyClass' object has no attribute 'attr2'  def do_sth1(self): print("do_sth1 was called")  from types import MethodType mc.do_sth1 = MethodType(do_sth1, mc) mc.do_sth1() # do_sth1 is called def do_sth2(self): print("do_sth2 was called")  # mc.do_sth2 = MethodType(do_sth2, mc) # mc.do_sth2() # AttributeError: 'MyClass' object has no attribute 'do_sth2'  """ By default, accessing attributes of an instance object is achieved by accessing the special attribute __dict__ of that instance object. E.g: Accessing obj.x actually accesses obj.__dict__['x']. After defining the special attribute __slots__ in the class object, its instance object will not create the special attribute __dict__, Instead, a descriptor is created for each property, which is called directly when the property is accessed. Calling the descriptor is faster than accessing __dict__, Therefore, defining the special attribute __slots__ in the class object can improve the access speed of the attribute. In addition, after defining the special attribute __slots__ in the class object, since its instance object no longer creates the special attribute __dict__, at the same time, The special attribute __dict__ is a dictionary. The essence of the dictionary is a hash table, which is a data structure that exchanges space for time. Therefore, defining the special attribute __slots__ in the class object can reduce memory consumption. """  # AttributeError: 'MyClass' object has no attribute '__dict__' # print(MyClass().__dict__)  """ The special attribute __slots__ only works on the instance object of its class object, and has no effect on the instance object of the subclass of its class object. If the subclass also defines the special attribute __slots__, then the instance object of the subclass has no effect. The names of properties and methods that can be dynamically bound are __slots__ of the subclass plus __slots__ of the parent class """  class MyChildClass1(MyClass): pass  mcc1 = MyChildClass1() mcc1.attr3 = 56  class MyChildClass2(MyClass): __slots__ = ("attr2", "do_sth2")  mcc2 = MyChildClass2()  mcc2.attr1 = 18 mcc2.attr2 = 18 mcc2.do_sth1 = 18 mcc2.do_sth2 = 18  # AttributeError: 'MyChildClass2' object has no attribute 'attr3' # mcc2.attr3 = 18 

◎Script address: https://github.com/anzhihe/learning/blob/master/python/practise/learn-python/python_advanced/special_attributes.py

This article is reprinted from: https://chegva.com/5288.html
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment