Namespaces for Python classes and objects

There are two properties that can be defined in a class

1. Static properties are stored in the namespace of the class

  • As long as it is an attribute of this class, it must have
  • Static properties of a class can be called using the class name
  • Static properties of a class can be called using an object

2. Dynamic properties

Namespaces for classes and objects

When a class is created, a namespace is created in memory

When an object is created, a namespace of the object is created. There is an identifier in the namespace of the object. This identifier class object pointer points to the class, so the object can find the class and access the static properties of the class.

For immutable data types, it is best to use the class name instead of the object name to operate the static properties of the class.

Because when an object operates a static attribute of a class, if there is no such attribute in the object, the object can access the static attribute of the class, but it cannot be modified. Once the modification operation is performed, it will be in the namespace of the object

To create this property, the operation is not a static property of the class

When there is an attribute name in the object with the same name as the static attribute of the class, the object operates on the attribute name in the object, and operates on the name in the object's own namespace

For mutable data types, the static property value of the object modification class is shared, and the re-copying is independent and creates a property in the object

It is not possible to directly find the specific object directly through the class

Global variables cannot be directly accessed in a class

class Course:   # 课程的意思     # 创建了一个类的命名空间在内存中
    language = 'Chines' # 静态属性,授课语言
    def __init__(self, teacher, course_name, period, price):
        self.teacher = teacher
        self.name = course_name
        self.period = period
        self.price = price


Course.language = 'English' # 通过类名修改类静态属性
print(Course.language)  # English
python = Course('egon', 'python', '6 month', '2W')  # 创建了一个对象的命名空间,有一个类对象指针指向了类,所以对象可以调用到类的静态属性
print(Course.language)  # English   可以通过python对象查看类的命名空间中的静态属性值

python.language = 'Chines'  # 无法修改类的静态属性,而是在python对象中创建了一个language属性被赋值为Chines
print(python.language)  # Chines
print(Course.language)  # English



# 认识绑定方法
    # 当一个对象名调用一个类内方法时,这个方法就和这个对象绑定在一起了
class Foo:  # 一个没有init方法的类,
    def func(self):
        print('func')

f1 = Foo()  # 实例化时直接返回了一个没有属性值的对象
f1.func()   # func  # 此时f1这个对象绑定了func方法,

Guess you like

Origin blog.csdn.net/Python_222/article/details/129938653