Encapsulation
1. Why encapsulation?
Encapsulation is to hide the specific implementation details of data attributes and methods, and only provide an interface. Encapsulation does not need to care about how the object is constructed
2. Encapsulation includes data encapsulation and function encapsulation. Data encapsulation is to protect privacy, and function encapsulation is to isolate complexity
3 .The encapsulation of data is to add a __
class People:def __init__(self,name,age,salary): self.name=name self.age=age self.__salary=salary p=People('zhang',19,100000)print(p.name)#zhangprint(p.age)#19print(p.__salary)#AttributeError: 'People' object has no attribute '__salary'
in front of the attribute. Hey, an error was reported. Let us open the namespace of the object and see what happened
print(p.__dict__)#{'name': 'zhang', 'age': 19, '_People__salary': 100000}
Oh, it turns out that python transformed __salary into _People__salary, do it again
print(p._People__salary)#100000
So, there is no absolute hiding in Python, as long as you know the above , it doesn’t matter if it is hidden.
These deformation operations only occur in the class definition phase or the object definition (instantiation phase) phase
Although the attributes added with __ cannot be directly accessed externally, But it can be accessed inside the class. You can understand it this way. During the definition phase, as long as it encounters something starting with __, the Python interpreter automatically recognizes it as the _class name__ attribute, so it can be accessed inside the class. In this case, We can do some little things
Let’s look at this first
class A:def foo(self):print('from A foo') self.bar()def bar(self):print('from A bar')class B(A):def bar(self):print('from B bar') b=B() b.foo() #from A foo
#from B bar 别想多了,调用函数时别看定义位置,要看调用位置
What if we just want to call the bar() function of the parent class? What to do
class A:def foo(self):print('from A foo') self.__bar()def __bar(self):print('from A bar')class B(A):def __bar(self):print('from B bar') b=B() b.foo() #from A foo#from A bar 有没有感受到编程的享受
4. Encapsulated application
1) Do not let the outside world see how our data attributes are defined, only through the interface we provide , see the content we allow the outside world to see
class People:def __init__(self,name,age,height,weight,hobby): self.__name=name self.__age=age self.__height=height self.__weight=weight self._hobby=hobbydef tell_info(self):print('''name:%s age:%s height:%s weeight:%s'''%(self.__name,self.__age, self.__height,self.__weight)) p=People('zhang',18,1.90,75,'read') p.tell_info()
2) A more common scenario is that we can limit the type of data, add our own logic and then encapsulate it to the user
def tell_name(self):print(self.__name)#修改名字def set_name(self,new):if not isinstance(new,str):raise TypeError('名字必须是字符串类型') self.__name=new
5. Looking at our above operation, when the user checks the name, he still has to p.tell_name(). It was originally a data attribute, but we turned it into a function. How to disguise it? After a while, you can use the built-in function property
class People:def __init__(self,name,age,height,weight,hobby): self.__name=name self.__age=age self.__height=height self.__weight=weight self._hobby=hobby @propertydef name(self):return self.__namep=People('zhang',18,1.90,75,'read')print(p.name)#zhang
The data attribute should also be modified and deleted
@propertydef name(self):return self.__name#name已经被property修饰过,就有setter和deleter @name.setterdef name(self,new):if not isinstance(new,str):raise TypeError('名字必须是字符串类型') self.__name=new @name.deleterdef name(self):del self.__namep = People('zhang', 18, 1.90, 75, 'read')print(p.name)#zhangp.name='can' #修改print(p.name)#candel p.name #删除print(p.name)#AttributeError: 'People' object has no attribute '_People__name'
The above is the detailed content of Python object-oriented knowledge summary. For more information, please follow other related articles on the PHP Chinese website!