09 ### 面向对象-修饰符 __? 私有变量

__? 表示是私有,私有得,只能内部才能访问

class Info:
    city = 'sc'
    __xx = 'xxx'  # __表示私有成员

    def __init__(self, name, age):
        self.name = name
        self.__age = age

    def show(self):
        print(self.__age)  # 通过内部函数进行调用
        print(self.__xx)  # 通过内部函数进行调用
        print(Info.__xx)  # 通过 类方法进行调用


obj = Info('tex', 29)
print(obj.name)
print(obj.__age)  # 报错 AttributeError: 'Info' object has no attribute '__age'
print(obj.show())  # 如果需要访问私有变量,需要在类方法中增加show 方法,通过内部进行调用私有变量

# 第二种访问私有成员变量 只有Flask上下文管理中有使用
class Info1:
    city = 'sc'
    __xx = 'xxx'  # __表示私有成员

    def __init__(self, name, age):
        self.name = name
        self.__age = age


obj = Info1('tex', 29)
print(obj.name)
# print(obj.__age)  # 报错 AttributeError: 'Info' object has no attribute '__age'
print(obj._Info1__age)  # 如果一定需要访问私有变量,可以使用:obj._Info1__age 创建的对象名._类名__私有变量名进行访问 obj._Info1__age

posted @ 2024-09-28 07:31  jhchena  阅读(11)  评论(0)    收藏  举报