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 are the concepts of object-oriented, superclass and abstraction in Python

2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article is a detailed introduction to "Python object-oriented, superclass and abstract concepts". The content is detailed, the steps are clear, and the details are properly handled. I hope this article "Python object-oriented, superclass and abstract concepts are" can help you solve your doubts. Let's go deeper and learn new knowledge together with the ideas of the small editor.

Object Magic

In object-oriented programming, the term object roughly means a set of data (attributes) and a set of methods for accessing and manipulating that data.

package

Packaging emphasizes structural reuse, logical introversion, and provides services to the outside with fixed interfaces. It follows a single responsibility, stipulating that each type has only one cause of change. The core of a single package is decoupling and cohesion, which makes the design simpler, clearer, the code easier to test and freeze, and avoids uncertainty.

inheritance

Inheriting adds new functionality or improves algorithms without changing the existing code and following the original design. It corresponds to the principle of opening and closing, closed to modification and open to expansion.

polymorphism

Polymorphism follows the Richter substitution principle, and all inherited subclasses should be able to be used directly in situations where they refer to parent classes.

We are used to stripping out the common parts of complex types to form solid abstract classes. Other similar triggers for change are separated into subcategories to ensure that a single responsibility is respected and replaced with one another.

We are used to stripping out the common parts of complex types to form solid abstract classes. Other similar triggers for change are separated into subcategories to ensure that a single responsibility is respected and replaced with one another.

Scenario: First abstract the overall framework into base classes, and then each subclass retains only a single branch logic.

inheritance and polymorphism

Define a class named Animal, and there is a run() method that prints directly:

class Animal(object):

def run(self):

print("Animal is running... ")

When we need to write Dog and Cat classes, we can inherit directly from Animal classes:

class Dog(Animal):

pass

class Cat(Animal):

pass

For Dog, Animal is its parent class, and for Animal, Dog is its subclass. Cat and Dog are similar.

The benefits of inheritance 1: the subclass gets all the functions of the parent class, and extends its own functions.

In the above example Animal implements the run() method, so Dog and Cat as its subclasses also have run() methods:

dog = Dog()

dog.run()

cat = Cat()

cat.run()

'''

Animal is running...

Animal is running...

'''

We can also extend the methods of subclasses, such as the Dog class:

class Dog(Animal):

def run(self):

print("Dog is running... ")

def dog_eat(self):

print("Eating bones... ")

Benefit of inheritance number two: overriding the functionality of the parent class.

Whether it's Dog or Cat, when they run(), it shows Animal is running... For Dog and Cat itself, it should have its own run() property, i.e. Dog is running.. And Cat is running... Therefore, improvements to the Dog and Cat classes are as follows:

class Dog(Animal):

def run(self):

print("Dog is running... ")

def dog_eat(self):

print("Eating bone... ")

class Cat(Animal):

def run(self):

print("Cat is running... ")

def cat_eat(self):

print("Eating fish... ")

if __name__ == "__main__":

dog = Dog()

dog.run()

cat = Cat()

cat.run()

'''

Dog is running...

Eating bone...

Cat is running...

Eating fish...

'''

When run() of a subclass overrides run() of a parent class, the runtime always calls run() of the subclass. In this way, we get another benefit of inheritance: polymorphism.

To determine whether a variable is of a certain type, you can use isinstance() to determine:

>>> isinstance(dog,Animal)

>>> isinstance(cat,Animal)

'''

True

True

'''

>>> isinstance(dog,Dog)

>>> isinstance(cat,Dog)

'''

True

False

'''

As you can see from the above example, the data type of dog is both Animal and Dog. Because Dog is inherited from Animal, when we create Dog instances, we think that the data type of dog is Dog, but at the same time dog is also the data type of animal, because Dog is originally a kind of Animal. The cat data type is Animal, but cat is not Dog.

Therefore, in inheritance relationships, if an instance's data type is a subclass, its data type can also be regarded as the parent class. But not the other way around:

>>> b = Animal()

>>> isinstance(b, Dog)

'''

False

'''

Dog can be seen as Animal, but Animal can not be seen as Dog.

superclass

To specify a superclass, append the superclass name to the class name in a class statement and enclose it in parentheses.

Filter is a generic class of filter sequences. In fact, it doesn't filter anything.

class Filter:

def init(self):

self.blocked = []

def filter(self, sequence):

return [x for x in sequence if x not in self.blocked]

class SPAMFilter(Filter):

# SPAMFilter is a subclass of Filter def init(self): #Overwrite method init of superclass Filter

def init(self): #Overwrite method init of superclass Filter

self.blocked = ['SPAM']

if __name__=="__main__":

f = Filter()

f.init()

print(f.filter([1, 2, 3]))

'''

1, 2, 3

'''

The Filter class is useful as a base class (superclass) for other classes, such as the SPAMFilter class, which filters 'SPAM' out of sequences.

if __name__=="__main__":

s = SPAMFilter()

s.init()

a = s.filter(['SPAM', 'SPAM', 'SPAM', 'SPAM', 'eggs', 'bacon', 'SPAM'])

print(a)

'''

['eggs', 'bacon']

'''

Note that there are two important points in the definition of the SPAMFilter class.

Overrides the definition of method init in the Filter class to provide a new definition.

The definition of the method filter is inherited directly from the Filter class, so there is no need to rewrite its definition.

The second point illustrates why inheritance is useful: you can create a large number of different filter classes, all derived from the Filter class, and all using the well-written method filter.

You can use the plural form__ bases __to learn the base class of a class, and there may be multiple base classes. To illustrate how to inherit multiple classes, let's create a few classes.

class Calculator:

def calculate(self, expression):

self.value = eval(expression)

class Talker:

def talk(self):

print('Hi, my value is',self.value)

class TalkingCalculator(Calculator, Talker): pass

if __name__=="__main__":

tc = TalkingCalculator()

tc.calculate('1 + 2 * 3')

tc.talk()

'''

Hi, my value is 7

'''

This is called multiple inheritance and is a powerful tool. However, multiple inheritance should be avoided except as a last resort, as in some cases it can cause unexpected "complications."

One important thing to note when using multiple inheritance is that if multiple superclasses implement the same method differently (i.e., have multiple methods with the same name), you must carefully arrange the superclasses in the class statement, because the methods of the preceding classes will override the methods of the following classes.

Thus, in the previous example, if the Calculator class contains the method talk, then this method overrides the Talker class's method talk (making it inaccessible).

If you reverse the order of superclasses like this:

class TalkingCalculator(Talker, Calculator): pass

The method that will cause Talker talk to be accessible. When multiple superclasses have the same superclass, the order in which the superclasses are accessed to find a particular method or attribute is called method resolution order (MRO), and it uses a very complex algorithm.

abstract base class

In general, an abstract class is a class that cannot be instantiated, and its responsibility is to define a set of abstract methods that the subclass should implement.

Here is a simple example:

from abc import ABC, abstractmethod

class Talker(ABC):

@abstractmethod

def talk(self):

pass

The point here is that you use @abstractmethod to mark methods as abstract-methods that must be implemented in subclasses.

If you are using an older Python version, you will not find the ABC class in module abc. In this case, you need to import ABCMeta and include the code line__ metaclass __ = ABCMeta at the beginning of the class definition (immediately after the class statement and indented). If you are using Python 3 versions prior to 3.4, you can also use Talker(metaclass=ABCMeta) instead of Talker(ABC).

The most important characteristic of abstract classes (i.e., classes that contain abstract methods) is that they cannot be instantiated.

>>> Talker()

Traceback (most recent call last):

File "", line 1, in

TypeError: Can't instantiate abstract class Talker with abstract methods talk

Suppose a subclass derives from it like this:

class Knigget(Talker):

pass

Since there is no override of the talk method, this class is abstract and cannot be instantiated. If you try to do this, an error message similar to the one before will appear. However, you can rewrite this class to implement the required methods.

class Knigget(Talker):

def talk(self):

print("Ni! ")

There is no problem instantiating it now. This is the main purpose of abstract base classes, and isinstance is appropriate only in this case: if you first check that a given instance is indeed a Talker object, you can believe that this instance has the method talk if needed.

>>> k = Knigget()

>>> isinstance(k, Talker) True

>>> k.talk()

Ni!

Read here, this article "Python object-oriented, superclass and abstract concept is what" article has been introduced, want to master the knowledge points of this article also need to practice to understand, if you want to know more about the content of the article, welcome to pay attention to the industry information channel.

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

Internet Technology

Wechat

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

12
Report