SoFunction
Updated on 2024-10-30

Description of private and public properties of python classes

python class private and public properties

For python, there are only two types of visibility for class attributes, public and private.

Private attributes of a class are preceded by the "__" identifier, while public attributes are not.

Accessing private attributes outside of a class throws an exception.

class Base:
    def __init__(self, value):
        self.__value = value
 
b = Base(5)
print(assert b.__value)
 
Traceback (most recent call last):
  File "/Users/yangjiajia/Desktop/project/python/algebra/", line 19, in <module>
    print(b.__value)
AttributeError: 'Base' object has no attribute '__value'

attribute is privatized and cannot be accessed even by word classes that inherit him.

class Parent:
    def __init__(self, value):
        self.__value = value 
 
class Child(Parent):
    def get_value(self):
        return self.__value
 
child = Child(4)
print(child.get_value())
 
Traceback (most recent call last):
  File "/Users/yangjiajia/Desktop/project/python/algebra/", line 24, in <module>
    print(child.get_value())
  File "/Users/yangjiajia/Desktop/project/python/algebra/", line 21, in get_value
    return self.__value
AttributeError: 'Child' object has no attribute '_Child__value'

Why is this? Because python does some transformations on the private properties of the class to keep the private fields private. When the compiler sees that the Child.get_value method is trying to access a private property, it transforms the __value to __Child_value and then accesses it, but in reality the private property is a __Parent__value. the word class can't access the parent class's private property, just because the name of the access is different.

Querying the object's property dictionary reveals

class Parent:
    def __init__(self, value):
        self.__value = value 
 
class Child(Parent):
    def name(self):
        names = 'yang'
 
    def get_value(self):
        return self.__value
 
child = Child(4)
print(child.__dict__)
 
{'_Parent__value': 4}

The principle of python development is still to use private attributes sparingly, and if you need to ensure that an attribute is not duplicated, you can precede it with a single underscore.

class Parent:
    def __init__(self, value):
        self._value = value 
 
class Child(Parent):
    def get_value(self):
        return self._value
 
child = Child(4)
assert child._value == 4

Definition of python private attributes

When you qualify a variable or method with private in Java, the method is only visible inside the entire class and is not visible or accessible from the outside.

There are also private attribute definitions in python, defined using two underscores prefixed to the function name.

For example __parameter

Next look at the previous Dog example

class Dog(object):
    __slots__ = ('__name', 'kind', 'level')
    def __init__(self,name,kind,level):# Constructor, defining properties and initial methods
        self.__name=name
        =kind
        =level#Assignment
        print(f"This is a {} dog called {self.__name} with level {}")
 
    def run(self):# Define the methods in the class
        print(f"{self.__name} is now running!")
 
    def roll_over(self):
        print(f"{self.__name} is now rolling over!")
 
    def change_level(self):
        +=1# Modify the value of a property in a class
        print(f"The level of {self.__name} is now {}")

Calling inside another file

from  import Dog# Guide packages
 
dog=Dog("Halo","Husty",3)# Instantiation
 
()
dog.roll_over()
dog.change_level()#invoke a method

Found that when we enter the following, it reports an error, illegal access.

print(dog.__name)

In this example, __name is a private qualification of name.

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.