Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the concept encapsulated in Python object-oriented

2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail what the concept of encapsulation in Python object-oriented is. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

A concept of encapsulation

In fact, packaging is everywhere in our lives, such as televisions, computers, mobile phones and other items. We usually only see its external shape and use the functions they provide, but not its internal complex hardware composition, which are encapsulated and cannot be seen by us to avoid some of our "special" operations. Make it not work properly. Programming comes from life. There is also an encapsulation operation on the object in python so that it only provides a fixed access mode to the outside, and cannot access its internal private properties and private methods. The encapsulation in python generally refers to the encapsulation of class attributes and class methods, that is, the privatization of class attributes and class methods, as described in the following summary.

II _ and _ _ privatization of properties and methods. Single underscore _

When the properties and methods in the class begin with a single underscore, it means that this is the class's protection variable and protection method, which, according to the coding convention, does not want to be accessed externally. But if you want to make an interview, you won't make a mistake.

As follows:

Class A (): # _ declaration is a protection attribute and protection method _ name = 'Zhang San' def _ _ init__ (self): self._age = 23 def _ method (self): print ("my name is {}, I am {} this year" .format (self._name Self._age)) if _ _ name__ = ='_ main__': a = A () # dir print of print class A (a. Print dirt _ ()) # access protection variable and protection method print (a._name) a._method ()

Output result:

> > >

['_ age','_ _ module__','_ name','_ _ init__','_ method','_ dict__','_ _ weakref__','_ _ doc__','_ _ repr__','_ _ hash__','_ str__','_ getattribute__','_ setattr__','_ _ delattr__','_ _ lt__' '_ _ le__',' _ _ eq__','_ _ ne__','_ _ gt__','_ _ ge__','_ _ new__','_ _ reduce_ex__','_ _ reduce__','_ _ subclasshook__','_ _ init_subclass__','_ format__','_ sizeof__','_ dir__','_ _ class__']

Zhang San

My name is Zhang San. I'm 23 years old.

As you can see, properties and methods that start with a single underscore are actually accessible outside the class, but by convention, when we see such properties and methods, we should not access them externally.

two。 Double underscore _ _

Although the above properties and methods that begin with a single underscore are protected, they are externally accessible. When you see properties and methods that start with a double underscore _ _, keep in mind that they are private properties and private methods of the class, and that methods that access class properties class methods outside the class and in subclasses cannot be accessed and cannot be modified, as follows

Class B (): # _ _ statement is privatized _ _ name = 'Zhang San' def _ _ init__ (self): self.__age = 23 self.__luange = 'python' def _ method (self): # Private method print ("my name is {}, I am {} this year, I like {}." .format (self.__name, self.__age, self.__luange) def fun (self): # Public method print ("this is a public method") if _ _ name__ ='_ _ main__': b = B () # dir print of print class B (b.printing dirt _ ()) # access the private attribute and private method b.fun () print of class B (b.__name) B.__age, b.__luange) b.__method ()

Output result:

> > >

['_ init__', dict__','_ weakref__','_ doc__','_ repr__','_ hash__','_ str__','_ getattribute__','_ setattr__' '_ _ delattr__',' _ _ lt__','_ _ le__','_ _ eq__','_ _ ne__','_ _ gt__','_ _ ge__','_ _ new__','_ _ reduce_ex__','_ _ reduce__','_ subclasshook__','_ init_subclass__','_ format__','_ _ sizeof__' '_ _ dir__',' _ _ class__']

This is a public method

Traceback (most recent call last):

File "C:/Users/admin/python-learning/python Learning File / python Foundation / python Class wrapper .py", line 56, in

Print (b.__name, b.__age, b.__luange)

AttributeError:'B' object has no attribute'_ _ name'

As you can see from the results, accessing the public method fun () of class B is normal, but when we access the private property name, we throw an error: class B has no name attribute. When we print the dir of class A when we underline it, we can see that the name property and method method of class A look like this in dir

We also printed the private properties and private methods of class B above, as follows:

You can see that private properties and private methods are in the form of _ name _ attribute and _ name _ method, so it is wrong for us to access them in the form of _ _ attribute or name, but if we use the class name (). _ class name _ _ attribute (instance property) or class name. If you access the _ class name _ _ attribute (class attribute), the access is successful. As follows

Class B (): # _ _ statement is privatized _ _ name = 'Zhang San' def _ _ init__ (self): self.__age = 23 self.__luange = 'python' def _ method (self): # Private method print ("my name is {}, I am {} this year, I like {}." .format (self.__name, self.__age Self.__luange)) def fun (self): # Public method print ("this is a public method") if _ _ name__ ='_ _ main__': b = B () # print class B's dir print (B. private dirt attributes _ ()) # access the private properties and private methods of class B b.fun () print (B._B__name, b._B__age) B._B__luange) b._B__method ()

The results are as follows:

> > >

['_ init__', dict__','_ weakref__','_ doc__','_ repr__','_ hash__','_ str__','_ getattribute__','_ setattr__' '_ _ delattr__',' _ _ lt__','_ _ le__','_ _ eq__','_ _ ne__','_ _ gt__','_ _ ge__','_ _ new__','_ _ reduce_ex__','_ _ reduce__','_ subclasshook__','_ init_subclass__','_ format__','_ _ sizeof__' '_ _ dir__',' _ _ class__']

This is a public method

Zhang San 23 python

My name is Zhang San. I'm 23 years old. I like python.

3. Access to private properties and private methods of the parent class in the subclass

The subclass cannot access the private properties and private methods of the parent class:

Class B (): # _ _ statement is privatized _ _ name = 'Zhang San' def _ _ init__ (self): self.__age = 23 self.__luange = 'python' def _ method (self): # Private method print ("my name is {}, I am {} this year, I like {}." .format (self.__name, self.__age, self.__luange) def fun (self): # Public method print ("this is a public method") class C (B): def _ _ init__ (self): super (). _ init__ () def fun1 (self): # access the private property and private method print (self.__name, self.__age) of parent class B. Self.__luange) self.__method () if _ _ name__ = ='_ main__': c = C () c.fun1 ()

Output result:

> > >

AttributeError:'C 'object has no attribute' _ Category name'

AttributeError:'C 'object has no attribute' _ Clearing methods

You can see that the subclass also cannot access the private properties and private methods of the parent class.

When the properties and methods in the subclass have the same name as the private properties and private methods of the parent class, the private properties and private methods of the parent class are not overwritten.

Class B (): # _ _ statement is privatized _ _ name = 'Zhang San' def _ _ init__ (self): self.__age = 23 self.__luange = 'python' def _ method (self): # Private method print ("my name is {}, I am {} this year, I like {}." .format (self.__name, self.__age Self.__luange)) def fun (self): # Public method print ("this is a public method") class C (B): _ _ name ='Li Si 'def _ _ init__ (self): super (). _ init__ () self.__age = 24 self.__luange =' clients' def fun1 (self): # access parent Private property of class B and private method print (self.__name Self.__age, self.__luange) self.__method () def _ _ method (self): # proprietary methods of class C It has the same name as the parent method, but does not override the parent method print ("my name is {}, I am {} this year, and I like {}." .format (self.__name, self.__age, self.__luange) # call the private method of the parent class B (). _ B__method () if _ _ name__ = ='_ main__': c = C () # access the private method of class C c._C__method ()

The results are as follows:

> > >

My name is Li Si. I'm 24 years old. I like C++.

My name is Zhang San. I'm 23 years old. I like python.

As you can see, subclass C does not override the _ _ method () method of parent class B. Why is that? Let's print the dir of B and C as follows:

> > >

['_ Backgroomed,'_ baked luangeaded,'_ clocked luangeaded,'_ clocked luangeaded, 'fun1'

'_ Clearing methods,' _ _ doc__','_ Barrier methods,'_ Bones methods,'_ Clearing methods,...]

As you can see, in the dir of class C, the private properties and methods of parent class B exist as _ attribute _ method, while the private properties and methods of class C exist as _ attribute _ method, that is, the private properties and methods of class will be stored in dir in the form of _ class name _ attribute (method). So when the properties and methods of the subclass have the same name as the private properties and methods of the parent class, the override is not overridden.

Access and modify private properties and methods of the class

Classes can be encapsulated and protected by privatizing properties and methods. But what happens when access and change are needed externally? Like televisions, computers also provide fixed interfaces.

Above, although we can use the class name (). _ class name _ _ attribute (instance property) or class name. _ class name _ _ attribute (class attribute) to access the private properties and private methods of the class, but this is against the programming specification and is not supported, just as it does not operate on the TV.

There are generally two ways to correctly modify the private properties and methods of a class, as follows:

1. Custom public method class D (): _ _ name = 'Zhang San' def _ _ init__ (self): self.__age = 23 self.__luange = 'python' def _ method (self): print ("my name is {}, I am {} this year, and I like {}." .format (self.__name, self.__age, self.__luange) def get_value (self): return self.__name, self.__age, self.__luange def get_method (self): self.__method () def set_value (self, name, age, luange): self.__name, self.__age, self.__luange = name, age Luangeif _ _ name__ = ='_ main__': d = D () # access the private attribute print (d.get_value ()) through the get_value method # access the private method print ('='* 30) d.get_method () # modify the private attribute print ('='* 30) print (d.get_) through the set_value method Value () d.set_value ('Wang er pockmarked' 25, 'Linux') print (d.get_value ()) d.get_method ()

Output result:

> > >

('Zhang San', 23, 'python')

= =

My name is Zhang San. I'm 23 years old. I like python.

= =

('Zhang San', 23, 'python')

('Wang er pockmarked', 25, 'Linux')

My name is Wang er pockmarked. I am 25 years old. I like Linux.

As you can see, we access and modify private properties and methods through custom get_value (), get_method (), and set_value () methods.

2. Property

Property generally has two functions, as follows:

As a decorator, @ property converts a class's methods to read-only class properties

Property reimplements the getter and setter methods of an attribute

Take a look at the following class E, as follows:

Class E (): _ _ name = 'Zhang San' def _ _ init__ (self): self.__age = 23 self.__luange = 'python' def _ method (self): print ("my name is {}, I am {} this year, and I like {}." .format (self.__name, self.__age, self.__luange) def get_value (self): return self.__name def set_value (self, name): self.__name = name getValue = property (get_value) Set_value) @ property def get_method (self): self.__method () if _ _ name__ = ='_ _ main__': e = E () # visit print (e.getValue) e.get_method # modify e.getValue = 'King II' print (e.getValue)

Results:

> > >

Zhang San

My name is Zhang San. I'm 23 years old. I like python.

Wang er

As you can see, when we pass the get_value and set_value methods into property, the class methods are converted to class properties and assigned to the getValue variable. At this point, e.getValue is read-only, that is, get_value method, and e.value = 'Wang er' is modification, that is, get_value method. Again, the get_method method is turned into an attribute through @ propert.

The following property reimplements the getter and setter methods of a property, which is different from the above and is more commonly used than the above.

Class E (): _ _ name = 'Zhang San' def _ _ init__ (self): self.__age = 23 self.__luange = 'python' def _ method (self): print ("my name is {}, I am {} this year, and I like {}." .format (self.__name, self.__age, self.__luange) @ property def name (self): return self.__name @ name.setter def name (self, name): self.__name = nameif _ _ name__ = ='_ main__': e = E () # access print (e.name) # modify print ("before modification:" E.name) e.name = 'Lao Wang' print ("revised:", e.name)

Output result:

> > >

Zhang San

Before revision: Zhang San

Revised: Lao Wang next door

The above is to first send the name method to the propert decorator for decoration, and then call the decorated setter method to modify the private properties.

This is the end of this article on "what is the concept encapsulated in Python object-oriented". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report