Home > Backend Development > Python Tutorial > Six questions about object-oriented Python

Six questions about object-oriented Python

王林
Release: 2023-04-11 20:43:13
forward
1129 people have browsed it

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
Copy after login

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__函数被调用')
self.title = title
self.author = author
self.__context = context

#类函数
@classmethod
def create_empty_book(cls, title, author):
return cls(title=title, author=author, context='nothing')

# 成员函数
def get_context_length(self):
return len(self.__context)

# 静态函数
@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'))
Copy after login

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()
Copy after login

Second type:

from abc import ABCMeta,abstractmethod
class A(metaclass = ABCMeta):
@abstractmethod
def fun(self):
pass
class B(A):
pass

b = B()
b.fun()
Copy after login

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---
Copy after login

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()
Copy after login

Output:

D is called
B is called
A is called
C is called
A is called
Copy after login

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()
Copy after login

Output;

enter D
enter B
enter C
enter A
levave A
levave C
levave B
levave D
Copy after login

第一种方法非常明确的表明了菱形继承潜在的问题:一个基类的初始化函数可能被调用两次。在一般的工程中,这显然不是我们所希望的。

正确的做法应该是使用 super 来召唤父类的构造函数,而且 python 使用一种叫做方法解析顺序的算法(具体实现算法叫做 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!

Related labels:
source:51cto.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template