Encapsulate what is encapsulation?
Hides the properties and implementation details of an object, providing public access only to the outside.
Benefits
- Isolate the changes
- Easy to use
- Improved reusability
- Improve security
Packaging principles
- To hide the content that does not need to be provided externally;
- Hides properties, providing public methods for accessing them.
Encapsulation method
Hide the attributes (set to private) in Python, which starts with an underscore, encapsulates
Private Property Private Property One
class Person: def __init__(self,height,weight,name,sex): self.__height = height # 私有属性:外部不能调用 self.weight = weight self.name = name self.sex = sex def tell_bmi(self): return self.weight / self.__height ** 2 def tell_height(self): # 建议这样查看值,用户不可以直接修改 return self.__height def set_height(self,new_height): # 建议这样修改值,即安全又人性化 self.__height = new_height if new_height > 20 else self.__height return self.__height # return不能返回赋值语句dennis = Person(1.75,120,‘dennis‘,‘man‘)print(dennis.tell_bmi())print(dennis.__dict__)print(dennis._Person__height)print(dennis.tell_height())print(dennis.set_height(-123)) # 设置不成功# 私有属性:# 在本类中就可以正常使用# 在本类外就必须_类名__属性名调用(不建议使用)
Private attribute Two
class Goods: __price = 3 ### 私有公共属性 def __init__(self,name,num): self.name = name self.num = num def goods_price(self): return self.num * Goods.__pricebanana = Goods(‘egon‘,2)print(banana.goods_price())print(Goods.__dict__)print(Goods._Goods__price)
Private methods
class Foo: def __init__(self,height,weight): self.height = height self.weight = weight def tell_bmi(self): return self.weight / self.__height_pow() def __height_pow(self): # 私有方法 return self.height ** 2dennis = Foo(1.7,125)print(dennis.tell_bmi())print(dennis._Foo__height_pow()) # 不建议
Property attribute what is
Property turns a method in a class into a method to implement
The @property implements read-only
@property X.setter implements a readable and writable (X.setter dependent @property,x method name for the decorated method)
class Goods: __discount = 0.8 # 类的私有属性 def __init__(self,name,price): self.name = name self.__price = price @property # 只读 def price(self): return self.__price * Goods.__discount @price.setter # 可写 def price(self,new_price): self.__price = new_price @price.deleter def price(self): del self.__price # 只能删除self赋值的命名# del self.name print(‘在执行删除操作啦!‘)apple = Goods(‘apple‘,20)print(apple.price)apple.price = 40print(apple.price)del apple.price # 删除会执行price.deleter里的# print(apple.price) # 因为删掉了__price,所以再次print会报错
To implement a class with Namedtuple only properties
from collections import namedtupleCourse = namedtuple(‘Course‘,[‘price‘,‘period‘,‘name‘])python = Course(20000,‘6 months‘,‘python‘)print(python.name)
From for notes (Wiz)
The path to Python-object-oriented encapsulation