Introduction to __mro__, __dict__ and dir in Python's class attributes, multiple inheritance, and introspection mechanisms

1. The difference between modifying attributes through class names and modifying class attributes through class instances

    In Python, attributes of a class can be accessed and modified through the class name or an instance of the class. However, there are some differences between modifying properties by class name and modifying properties by instance of the class. Modifying properties by class name is actually modifying the properties of the class. This means that if you modify a property of a class, all instances of that class will be affected .

class Person(object):
    # 类属性
    name = "人类"




Person.name = "小博"
zs = Person()
ls = Person()
print(zs.name, ls.name)
以上案例运行后输出:小博 小博

    Modifying properties through an instance of a class actually creates or modifies properties of the instance. This means that if you modify a property of an instance, only that instance will be affected, not other instances of the class or the class itself .

class Person(object):
    # 类属性
    name = "人类"




zs = Person()
zs.name = "张三"
ls = Person()
print(zs.name,ls.name,Person.name)
以上代码运行输出:张三 人类 人类

Second, the calling order of multiple inheritance

class A:
    def foo(self):
        print("A's foo")




class B(A):
    def foo(self):
        print("B's foo")
        super().foo()




class C(A):
    def foo(self):
        print("C's foo")
        super().foo()




class D(B, C):
    pass




obj = D()
obj.foo()

After running the above code, the output is as follows:

B's foo
C's foo
A's foo

In the multiple inheritance of python3, the method resolution order (MRO) is implemented based on the C3 algorithm, which ensures that the resolution order is in order.

3. Introduction to the __mro__ attribute of the class

As in the above example, if you don't know the order of calls and guess here, try

print(D.__mro__), then you will see the following output:

(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)

__mro__ is a special attribute, which is a tuple representing the method resolution order (MRO) of a class, that is, the order in which attributes and methods are looked up. It is automatically calculated by Python when performing inheritance

4. Introduction to the introspection mechanism of python

Python's introspection mechanism (introspection) refers to the ability to obtain information such as the type, attributes, and methods of an object at runtime (runtime). Python's introspection mechanism is very powerful, allowing developers to be more flexible and efficient when writing programs.

Here are a few built-in functions and special attributes provided in python to support the introspection mechanism:

__dict__ : It is used to store the attributes and methods of an object. The __dict__ attribute allows the program to dynamically add, modify, and delete the attributes and methods of the object at runtime, thereby realizing advanced functions such as reflection and metaprogramming.

In Python, the __dict__ attribute of an object can usually be modified, but there are some objects whose __dict__ attribute is read-only and cannot be modified directly. Here are some common object types and their __dict__ attribute modifications:

1. The __dict__ attribute of an ordinary object instance can be modified at will, allowing dynamic addition, modification, and deletion of object attributes and methods

2. The __dict__ attribute of classes, modules, and some built-in objects (such as str) is read-only, because the attributes and methods of classes and modules are determined at the time of definition and cannot be modified at runtime. The attributes and methods of built-in objects are Implemented by the interpreter and cannot be modified at runtime.

3. In Python, int and str objects are immutable objects, and their __dict__ attribute does not exist. Because the attributes and methods of immutable objects are determined at definition time and cannot be dynamically added, modified, and removed at runtime, they also do not require a __dict__ attribute to hold attributes and methods.

f5b3fcfbf7f9f5dc49f65583d1f45a79.png

dir() function : Get the attribute list of the object. For example, dir(obj) returns a list of the names of all properties and methods of the object obj.

print(dir(str))

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

After reading the above content, leave a question for you in front of the screen. What is the output of the following code after running?

245670517c5cbe1b06257f842e56f109.png

If you have gained something after reading the article I wrote, please like it and forward it to support it. Friends who want to learn with the editor can chat privately~

Guess you like

Origin blog.csdn.net/liboshi123/article/details/130279070