Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Biến public và private trong class Python

Public Variables

Python không hạn chế truy cập biến hay gọi method. Mọi biến và method mặc định là public.

class Mug:
    def __init__(self):
        self.color = None
        self.content = None
    
    def fill(self, beverage):
        self.content = beverage
    
    def empty(self):
        self.content = None

mug = Mug()
mug.color = "brown"
mug.fill('tea')
print(mug.color)    # brown
print(mug.content)  # tea

Private Variables (mô phỏng)

Python dùng name mangling: tên bắt đầu bằng __ (ít nhất 2 underscore) và kết thúc tối đa 1 underscore sẽ bị biến đổi thành _ClassName__memberName.

class Cup:
    def __init__(self, color):
        self.__content = None  # private variable
    
    def fill(self, beverage):
        self.__content = beverage
    
    def empty(self):
        self.__content = None

cup = Cup("red")
cup.fill("tea")
# cup.__content  # AttributeError

# Vẫn truy cập được qua mangled name (không khuyến khích)
cup._Cup__content = "coffee"

Tóm tắt:

  • public: mặc định, không prefix
  • _semi_private: quy ước internal use
  • __private: name mangling, tránh va tên subclass