search
HomeBackend DevelopmentPython TutorialPython object-oriented knowledge summary

Python object-oriented knowledge summary

Jul 23, 2017 pm 01:44 PM
pythonprogrammingFor

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?What should I do if the '__builtin__' module is not found when loading the Pickle file in Python 3.6?Apr 02, 2025 am 07:12 AM

Error loading Pickle file in Python 3.6 environment: ModuleNotFoundError:Nomodulenamed...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use