# 廣義上的封裝# class 類名:# def 方法名(self):pass# 是爲了只有這個類的對象才胡使用定義在類中的方法# 狹義上的封裝: 把一個名字藏在類中class Goods: __discount = 0.2 # 私有的靜態變量 print(__discount) # 0.2# 在類的外部不能引用私有的靜態變量# 類中的靜態變量和方法名,在程序加載 的過程 中,已經執行完了,不須要等待調用# 在這個類加載完成 以前,Goods這個類名,還沒見有出如今全局名稱空間中# 私有的靜態變量能夠在類的內部使用,用來隱藏某個變量的值。print(Goods.__dict__) # {'__module__': '__main__', '_Goods__discount': 0.2, '__dict__': <attriclass Goods: __discount = 0.7 # 私有的靜態變量# 變形: _類名__私有變量# print(Goods.__discount) # AttributeError: type object 'Goods' has no attribute '__discount' 類對象沒有這個屬性print(Goods._Goods__discount) # 這樣能夠從類的外部訪問,可是從編程規範的角度上出發,不建議在類的外部# 使用私有的靜態變量class Student: def __init__(self,name,age): self.__name = name # 對象的私有變量,類外部,不能操做 self.age = age def getName(self): return self.__namestudent = Student("王小寶",28)# print(student.__name) # 報錯,對象沒有這個屬性print(student.getName()) # 王小寶 這是經過類中的方法,來操做對象的私有變量print(student.__dict__) # {'_Student__name': '王小寶', 'age': 28} 對象的屬性,是存在對象的名稱空間中的,而且對於# 對象的私有變量,也做了一個變形,以對象所屬的直接類 _類名__私有變量print(student.age)student.age = "aaaa" # python是弱類型 語言print(student.age)class Goods: __discount = 0.6 # 私有的靜態變量 def __init__(self,name,price): self.name = name self.__price = price # 我不想讓你看到這個值 def getPrice(self): return self.__price * self.__discount def changePrice(self,newPrice): # 我想讓你修改一個值的時候有一些限制 if type(newPrice) is int: self.__price = newPrice else: print("本次價格修改不成功")pear = Goods("pear",89)print(pear.getPrice()) # 53.4pear.changePrice(100) # 將價格改成100print(pear.getPrice()) # 60.0class User: def __init__(self,username,password): self.username = username self.__pwd = password self.pwd = self.__getpwd() def __getpwd(self): return hash(self.__pwd)user = User("chirs",'jiayong')print(user.pwd) # -4615835297725458545# 類中的私有成員# 私有的靜態變量# 私有的對象變量# 私有的方法# 私有的變量,在內存中存儲時 會 變形,在使用時,也會變形# 爲何要定義一 個私有變量呢?# 不想讓你看到這個變量# 不想讓你修改這個變量# 想讓你修改這個變量有一些限制# 有些方法或屬性不但願被子類繼承## 廣義上的封裝,把屬性和函數都放到類裏# 狹義上的封裝,定義 私有成員# 私有變量能不能 在類的外部 定義 ????class A: __private = 1000 print(__private) def getAge(self): print(self.__age)print(A.__dict__) # {'__module__': '__main__', '_A__private': 1000, '__dict__': <attribprint(A._A__private) # 1000A.__language = "chinese"print(A.__dict__)A._A__age = 18 # 經過 這種方式,能夠在外部定義一個私有的靜態屬性print(A.__dict__)print(A._A__age) # 18A.getAge(A) # 18# 私有變量能不能被繼承???class A: age = 100 __country = "china" def __init__(self,name): self.__name = name # 存儲時 變形 _A__nameclass B(A): # print(age) # NameError: name 'age' is not defined # print(__country) def getName(self): return self.__name # _B__nameb = B("jeason")print(b.__dict__)# b.getName() # AttributeError: 'B' object has no attribute '_B__name'# 結論: 對於 類中的私有變量 ,在那個類中,變量時,就是那個類的名字 和 下劃線打頭 : _類名__私有變量