私有屬性和私有方法

01.應用場景及定義方式

class Women:
    def __init__(self,name):

        self.name = name
        self.__age = 18 # 屬性前面加兩個下劃線就是私有屬性

    #def secret(self): # 方法前面加兩個下劃線就是私有方法
    def __secret(self):
        # 在對象的方法內部,是能夠訪問對象的私有屬性的
        print("%s 的年齡是 %d"% (self.name,self.__age))

xiaofang = Women("小芳")
# 私有屬性在外界不可以被直接訪問
# print(xiaofang.__age)
# 私有方法,一樣不能直接被外界訪問
# xiaofang.__secret()

02.僞私有屬性和私有方法

相關文章
相關標籤/搜索