This article is written for friends who are new to Python, trying to clarify the following questions:
- What are classes and objects?
- Now that there are functions, why do we need classes?
- How does Python define public/protected/private properties/methods? Is private really private? What is the purpose of doing so?
- How to define class functions, member functions, and static functions? They are What are the functions?
- Classes can be inherited, how to make subclasses have to rewrite the functions of the parent class before they can be used, otherwise an exception will be thrown?
- There are the following inheritance relationships: A, B (A),C(A),D(B,C) So when D is initialized, what is the initialization order of A, B, and C? Will A be initialized twice?
1. What are classes and objects?
Let’s talk about objects first. Objects usually have two meanings. They refer to things that are the goal when acting or thinking, or specifically to the person you are in love with. In the world of programming, objects are the mapping of people, things, objects and other entities that exist in the objective world in computer logic.
When programming, you can map objects to anything you want to map. However, if the mapping is more conventional, the code will be easier to use and understand, and it will be more conducive to subsequent rapid iteration and expansion. . In the world of Python, everything is an object.
Let’s talk about classes. Classes are classified classes, which represent a collection of similar things and correspond to the Python keyword class.
An object is a specific thing in a class, which is generated after initialization of the class. It is usually also called object, or entity. For example, a woman is a class, and your girlfriend is an object.
Attribute: A certain static characteristic of the object, such as your girlfriend’s skin color, ethnicity, blood type, etc.
Function: A certain dynamic ability of the object, such as your girlfriend can sing, play the piano, etc.
Although the example given may not be appropriate, I hope it can deepen your understanding. In fact, the more precise definition is as follows:
A class is a group of objects with the same attributes and functions. collection.
2. Now that there are functions, why do we need classes?
Functions are to solve code reuse, but functions are process thinking, too specific, too specific There will be a lot of duplication of things, so we also need to abstract the problem, and classes are a kind of abstraction. Abstract classes are more reusable, easier to face complex business logic, and will also ease programmers' programming memory pressure.
If there were no classes, it would be easier for us to write a mountain of code that would affect the whole body and not dare to modify it. With classes, it is easier for us to write code that is easy to read, easy to maintain, and extensible.
3. How does Python define public/protected/private properties/methods? Whether private is truly private, what is the purpose of doing so?
Python agrees on protected/private in the following form Attributes/methods:
- __ means private
- _ means protection
- Except for the first two, it is public
The so-called agreement , that is, when you see a variable or method starting with a double underscore or a single underscore, you should consciously not modify or access it outside the class. In other words, Python will not prevent programmers from accessing the private attributes or private methods of the class. Python chooses Trust programmers.
There is no difference between accessing public properties and accessing protected properties. To access private properties, you need to do this:
object._ClassName__PrivateMember
4. How to define class functions, member functions, and static functions, and what are their functions?
Look at the comments:
class Document(): WELCOME_STR = 'Welcome! The context for this book is {}.' def __init__(self, title, author, context): print('__init__函數(shù)被調(diào)用') self.title = title self.author = author self.__context = context #類函數(shù) @classmethod def create_empty_book(cls, title, author): return cls(title=title, author=author, context='nothing') # 成員函數(shù) def get_context_length(self): return len(self.__context) # 靜態(tài)函數(shù) @staticmethod def get_welcome(context): return Document.WELCOME_STR.format(context) empty_book = Document.create_empty_book('What Every Man Thinks About Apart from Sex', 'Professor Sheridan Simove') print(empty_book.get_context_length()) print(empty_book.get_welcome('indeed nothing'))
The class function is decorated with @classmethod. The first parameter must be cls, which represents the class itself. In other words, we can call the class constructor in the classmethod function. Function cls(), thereby generating a new instance. From this point, we can infer its usage scenarios:
- When we need to call the constructor again, that is, when creating a new instance object
- We need not to modify the existing instance case returns a new instance.
Member functions are very common, they are methods that can be called directly by the object. The first parameter must be self.
Static function, decorated with @staticmethod, usually means that the calculation of this function does not involve the variables of the class, and it can be used without instantiation of the class, which means that the relationship between the function and this class is not very close. , In other words, functions decorated with staticmethod can also be defined outside the class. I sometimes struggle with whether to use staticmethod in a class or write a separate function in utils.py.
5. Classes can be inherited. How to make subclasses have to rewrite the functions of the parent class before they can be used, otherwise an exception will be thrown?
Two methods, the second one is recommended.
First type:
class A: def fun(self): raise Exception("not implement") class B(A): pass b = B() b.fun()
Second type:
from abc import ABCMeta,abstractmethod class A(metaclass = ABCMeta): @abstractmethod def fun(self): pass class B(A): pass b = B() b.fun()
6. There are the following inheritance relationships: A, B(A), C(A), D(B ,C) So when D is initialized, what is the initialization order of A, B, and C? Will A be initialized twice?
---> B--- A--->D ---> C---
What is the initialization order of A, B, and C? You might as well write some code and take a look.
There are two ways. The first way A will be initialized twice, and the second way will not.
First type:
class A: def __init__(self): print("A is called")class B(A): def __init__(self): print("B is called") A.__init__(self)class C(A): def __init__(self): print("C is called") A.__init__(self)class D(B,C): def __init__(self): print("D is called") B.__init__(self) C.__init__(self) d = D()
Output:
D is called B is called A is called C is called A is called
Second type:
class A: def __init__(self): print("enter A") print("levave A")class B(A): def __init__(self): print("enter B") super().__init__() print("levave B")class C(A): def __init__(self): print("enter C") super().__init__() print("levave C")class D(B,C): def __init__(self): print("enter D") super().__init__() print("levave D") d = D()
Output;
enter D enter B enter C enter A levave A levave C levave B levave D
第一種方法非常明確的表明了菱形繼承潛在的問題:一個基類的初始化函數(shù)可能被調(diào)用兩次。在一般的工程中,這顯然不是我們所希望的。
正確的做法應(yīng)該是使用 super 來召喚父類的構(gòu)造函數(shù),而且 python 使用一種叫做方法解析順序的算法(具體實現(xiàn)算法叫做 C3),來保證一個類只會被初始化一次。
也就是說,能用 super,就用 super。
The above is the detailed content of Six questions about object-oriented Python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

Python is an efficient tool to implement ETL processes. 1. Data extraction: Data can be extracted from databases, APIs, files and other sources through pandas, sqlalchemy, requests and other libraries; 2. Data conversion: Use pandas for cleaning, type conversion, association, aggregation and other operations to ensure data quality and optimize performance; 3. Data loading: Use pandas' to_sql method or cloud platform SDK to write data to the target system, pay attention to writing methods and batch processing; 4. Tool recommendations: Airflow, Dagster, Prefect are used for process scheduling and management, combining log alarms and virtual environments to improve stability and maintainability.

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

shutil.rmtree() is a function in Python that recursively deletes the entire directory tree. It can delete specified folders and all contents. 1. Basic usage: Use shutil.rmtree(path) to delete the directory, and you need to handle FileNotFoundError, PermissionError and other exceptions. 2. Practical application: You can clear folders containing subdirectories and files in one click, such as temporary data or cached directories. 3. Notes: The deletion operation is not restored; FileNotFoundError is thrown when the path does not exist; it may fail due to permissions or file occupation. 4. Optional parameters: Errors can be ignored by ignore_errors=True

Install the corresponding database driver; 2. Use connect() to connect to the database; 3. Create a cursor object; 4. Use execute() or executemany() to execute SQL and use parameterized query to prevent injection; 5. Use fetchall(), etc. to obtain results; 6. Commit() is required after modification; 7. Finally, close the connection or use a context manager to automatically handle it; the complete process ensures that SQL operations are safe and efficient.

ChromecanopenlocalfileslikeHTMLandPDFsbyusing"Openfile"ordraggingthemintothebrowser;ensuretheaddressstartswithfile:///;2.SecurityrestrictionsblockAJAX,localStorage,andcross-folderaccessonfile://;usealocalserverlikepython-mhttp.server8000tor

Use multiprocessing.Queue to safely pass data between multiple processes, suitable for scenarios of multiple producers and consumers; 2. Use multiprocessing.Pipe to achieve bidirectional high-speed communication between two processes, but only for two-point connections; 3. Use Value and Array to store simple data types in shared memory, and need to be used with Lock to avoid competition conditions; 4. Use Manager to share complex data structures such as lists and dictionaries, which are highly flexible but have low performance, and are suitable for scenarios with complex shared states; appropriate methods should be selected based on data size, performance requirements and complexity. Queue and Manager are most suitable for beginners.
