(100 days, 2 hours, fourth day) class attributes and methods

Private: add double underscore in front to represent private

Private attributes of the class: __private_attrs : start with two underscores, declare that the attribute is private and cannot be used or directly accessed outside the class. Self.__private_attrs is used in methods inside the class  .

Class method: inside the class, you can use the def keyword to define a method for the class. Unlike general function definitions, the class method must include the parameter self, which is the first parameter

The private method of the class: __private_method : starting with two underscores, declare that the method is a private method and cannot be called outside the class. Call self.__private_methods inside the class 

Note: The instance cannot access private variables.

class JustCounter:
    __secretCount = 0  # 私有变量
    publicCount = 0    # 公开变量
 
    def count(self):
        self.__secretCount += 1
        self.publicCount += 1
        print self.__secretCount
 
counter = JustCounter()
counter.count()
counter.count()
print counter.publicCount
print counter.__secretCount  # 报错,实例不能访问私有变量

Python does not allow instantiated classes to access private data, but you can use object._className__attrName ( object name._class name__private  attribute name  ) to access attributes.

class JustCounter:
    __secretCount = 0  # 私有变量
    publicCount = 0  # 公开变量

    def count(self):
        self.__secretCount += 1
        self.publicCount += 1
        print(self.__secretCount)


counter = JustCounter()
counter.count()
counter.count()
print(counter.publicCount)
print(counter._JustCounter__secretCount)  # 对象名.类名_私有变量 可以访问

  

Single underline, double underline, head and tail double underline description:

  • __foo__ : defines a special method, usually a system-defined name, similar to __init__() and the like.

  • _foo : The one that starts with a single underscore represents the variable of the protected type, that is, the protected type can only allow access to itself and subclasses , and cannot be used from module import *

      __foo : The double underscore indicates a variable of private type (private), which can only be accessed by the class itself .

Guess you like

Origin blog.csdn.net/zhangxue1232/article/details/109368258