类的私有变量

2020-08-05  本文已影响0人  cc_cv
class Person(object):
    public_var = "公有"                     # 类的静态变量,由类调用,子类可访问
    __private_var = "私有"                  # 类的私有变量,只能由类内部调用,类外部及子类不能访问
    def __init__(self, name, age):
        self.name = name                    # 实例的成员变量,由对象调用self.name,子类可访问
        self.__age = age                    # 实例的私有变量,只能由类内部调用,类外部及子类不能访问
    @classmethod
    def class_func(cls):                    # 类的方法,由类调用Person.class_func(),子类和子类的实例都可以访问
        print ("class method")
    @staticmethod
    def static_func():                      # 类的静态方法,由类调用Person.static_func(),子类和子类的实例都可以访问
        print ("static method")
    def comm_func(self):                    # 实例的方法,由对象调用self.comm_func()
        print ("{} is {} years old.".format(self.name, self.__age))
    def __private_func(self):               # 类的私有方法,只能由类内部调用,类外部及子类不能访问
        print ("The value of __private_var is {}.".format(self.__private_var))
    def proxy_private(self):
        self.__private_func()
    @property
    def age(self):                          # 属性封装,由对象调用self.age
        return self.__age

class Student(Person):
    pass

>>> s = Student("Tom", 18)
>>> s.public_var
'公有'
>>> s.__private_var                            # 类的私有变量,只能由类内部调用,类外部及子类不能访问
Traceback (most recent call last):
  File "<pyshell#89>", line 1, in <module>
    s.__private_var
AttributeError: 'Student' object has no attribute '__private_var'
>>> s.name
'Tom'
>>> s.__age                                # 实例的私有变量,只能由类内部调用,类外部及子类不能访问
Traceback (most recent call last):
  File "<pyshell#91>", line 1, in <module>
    s.__age
AttributeError: 'Student' object has no attribute '__age'
>>> s.comm_func()
Tom is 18 years old.
>>> s.age
18
>>> s.__private_func()                          # 类的私有方法,只能由类内部调用,类外部及子类不能访问
Traceback (most recent call last):
  File "<pyshell#94>", line 1, in <module>
    s.__private_func()
AttributeError: 'Student' object has no attribute '__private_func'
>>> s.proxy_private()
The value of __private_var is 私有.
>>> Student.class_func()
class method
>>> s.class_func()
class method
>>> Student.static_func()
static method
>>> s.static_func()
static method
>>>

上一篇下一篇

猜你喜欢

热点阅读