Python class members and instance members, private members and public members, code examples

In Python, class members refer to the variables or methods defined in the class definition, and instance members refer to the variables or methods owned by each instance during the instantiation of the class. A private member refers to adding a double underscore "__" before the variable or method name, which can only be accessed inside the class and cannot be accessed outside. Public members refer to variables or methods without double underscores, which can be accessed inside and outside the class.


下面是一个简单的示例代码:

```python
class MyClass:
    # 公有类成员
    class_var = "I am a class variable"

    def __init__(self, arg1, arg2):
        # 实例变量
        self.arg1 = arg1
        self.arg2 = arg2
        # 私有实例变量
        self.__private_var = "I am a private instance variable"

    # 公有实例方法
    def public_method(self):
        print("I am a public instance method")

    # 私有实例方法
    def __private_method(self):
        print("I am a private instance method")

# 访问公有类成员
print(MyClass.class_var)

# 实例化类
my_obj = MyClass("arg1_value", "arg2_value")

# 访问实例变量
print(my_obj.arg1)
print(my_obj.arg2)

# 访问公有实例方法
my_obj.public_method()

# 访问私有实例变量(会报错)
# print(my_obj.__private_var)

# 访问私有实例方法(会报错)
# my_obj.__private_method()
```

In the above code, `class_var` is a public class member that can be accessed directly by the class name. `arg1` and `arg2` are instance variables, each with its own value. `public_method` is a public instance method that can be called through instance objects. `__private_var` and `__private_method` are private instance members that can only be accessed inside the class and cannot be accessed outside. If a private member is accessed externally, an error will be reported.

Guess you like

Origin blog.csdn.net/babyai996/article/details/131140014