国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
1. What are classes and objects?
2. Now that there are functions, why do we need classes?
3. How does Python define public/protected/private properties/methods? Whether private is truly private, what is the purpose of doing so?
4. How to define class functions, member functions, and static functions, and what are their functions?
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?
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?
Home Backend Development Python Tutorial Six questions about object-oriented Python

Six questions about object-oriented Python

Apr 11, 2023 pm 08:43 PM
python programming mapping

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!

Statement of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Using std::chrono in C Using std::chrono in C Jul 15, 2025 am 01:30 AM

std::chrono is used in C to process time, including obtaining the current time, measuring execution time, operation time point and duration, and formatting analysis time. 1. Use std::chrono::system_clock::now() to obtain the current time, which can be converted into a readable string, but the system clock may not be monotonous; 2. Use std::chrono::steady_clock to measure the execution time to ensure monotony, and convert it into milliseconds, seconds and other units through duration_cast; 3. Time point (time_point) and duration (duration) can be interoperable, but attention should be paid to unit compatibility and clock epoch (epoch)

How to read a JSON file in Python? How to read a JSON file in Python? Jul 14, 2025 am 02:42 AM

Reading JSON files can be implemented in Python through the json module. The specific steps are: use the open() function to open the file, use json.load() to load the content, and the data will be returned in a dictionary or list form; if you process JSON strings, you should use json.loads(). Common problems include file path errors, incorrect JSON format, encoding problems and data type conversion differences. Pay attention to path accuracy, format legality, encoding settings, and mapping of boolean values and null.

Python for loop range Python for loop range Jul 14, 2025 am 02:47 AM

In Python, using a for loop with the range() function is a common way to control the number of loops. 1. Use when you know the number of loops or need to access elements by index; 2. Range(stop) from 0 to stop-1, range(start,stop) from start to stop-1, range(start,stop) adds step size; 3. Note that range does not contain the end value, and returns iterable objects instead of lists in Python 3; 4. You can convert to a list through list(range()), and use negative step size in reverse order.

How to iterate over a string in Python How to iterate over a string in Python Jul 14, 2025 am 02:04 AM

There are many ways to traverse strings in Python, depending on the requirements. First, using a for loop, you can directly access characters one by one: s="hello", forcharins:print(char), and each character will be output in turn. Secondly, if you need index information, you can combine the enumerate() function: s="hello", forindex,charinenumerate(s):print(f"Position{index}:{char}"), so as to obtain the characters and their positions at the same time. In addition, list comprehension is suitable for batch processing of characters

Go struct tags Go struct tags Jul 14, 2025 am 02:17 AM

In Go language, structtags is meta information attached to the structure field, which is used to control serialization, deserialization behavior or provide library configuration. 1.structtags are written in backticks in key:"value" format, such as json:"name", which determines the serialization method of the field; 2. Multiple tags can coexist, and each library parses the required parts, such as json and gorm together; 3. Mapstructure is used to configure mapping, and supports omitting tags and nested structures when the field names are consistent; 4. Pay attention to avoid spelling errors, fields need to be exported, and tags cannot be abused to affect readability. Mastering its usage will help improve development efficiency and generation

Python JSON load from URL Python JSON load from URL Jul 14, 2025 am 02:13 AM

The method of loading JSON data from URLs in Python is as follows: 1. Use the requests library to initiate a GET request and parse the response; 2. The optional json module cooperates with urllib processing. The specific steps are: first download the data through requests.get(), and use response.json() to convert the format, and check the status code to ensure the successful request; if you need to avoid third-party libraries, you can use urllib.request to combine json.loads() to manually parse it. Frequently asked questions include JSON format errors, connection timeouts, encoding mismatches, etc., which can be solved by setting timeouts, adding headers, or debugging output. The entire process requires that the URL is valid and the server is resounding normally

Python for loop to read file line by line Python for loop to read file line by line Jul 14, 2025 am 02:47 AM

Using a for loop to read files line by line is an efficient way to process large files. 1. The basic usage is to open the file through withopen() and automatically manage the closing. Combined with forlineinfile to traverse each line. line.strip() can remove line breaks and spaces; 2. If you need to record the line number, you can use enumerate(file, start=1) to let the line number start from 1; 3. When processing non-ASCII files, you should specify encoding parameters such as utf-8 to avoid encoding errors. These methods are concise and practical, and are suitable for most text processing scenarios.

python case-insensitive string compare if python case-insensitive string compare if Jul 14, 2025 am 02:53 AM

The most direct way to make case-insensitive string comparisons in Python is to use .lower() or .upper() to compare. For example: str1.lower()==str2.lower() can determine whether it is equal; secondly, for multilingual text, it is recommended to use a more thorough casefold() method, such as "stra?".casefold() will be converted to "strasse", while .lower() may retain specific characters; in addition, it should be avoided to use == comparison directly, unless the case is confirmed to be consistent, it is easy to cause logical errors; finally, when processing user input, database or matching

See all articles