This is the 19th day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021

preface

We’ve covered the main built-in object types in Python (numbers, strings, lists, tuples, and dictionaries). And the core object oriented people have yet to show up. So what is the type of object we often say? In fact, its type is “class”. Inheritance encapsulation and polymorphism are common object-oriented programming ideas.

Inheritance in Python

Inheritance is designed to improve code reuse, and subclasses can implement methods in their superclass by inheriting from their superclass, which is just plain lazy. For example:

class Person(): def eat(self): print("person can eat ..." ) def slepp(self): print("person can slepp ..." ) calss Man(Person): def hardWork(self): print("man should be work hard ..." ) # test m = Man() m.eat() # person can eat...Copy the code

First of all, you define a class using the class keyword, you define a method using def, and you pass in an argument by default, which doesn’t have to be called self but for identification purposes, we define it this way, because it represents the current object, just like this in Java. And of course, our inheritance is defined by a parenthesis plus a superclass, so why didn’t we say “Person”, because we’ve omitted an “object” which means we inherit the “Object” superclass by default. In addition, Python supports multiple inheritance, such as calss Man(Animal,Person). However, multiple inheritance is not recommended.

Encapsulation in Python

Encapsulation, simple to understand, is to hide attribute information in a class and provide public methods to be called. We “privatize” the attribute by adding two underscores __name to the attribute to define a fake private attribute. See the examples:

Self.__name = "" def set_name(self,name): self.__name = name def get_name(self): Return self.__name m = Man() # create object m.set_name('YJK923') # set name(_Man__name) m.goet_name () # obtain name( _Man__name) 'YJK923' m.name = 'YJK' # add attribute name m.get_name() 'YJK923' m.name # Get the value of the name just created for m. 'YJK' m._Man__name # Get the attribute _Man__name. This is where Python gets the trick: it's not privatized, it's just formatted. 'YJK923'Copy the code

Polymorphism in Python

There is also polymorphism, simple understanding, is that there are many states, common is the same method but the effect of execution is not the same, just like there are too many people with the same name, but each person is different, see, programming ideas are also from daily life. For example, both are sleeping, but some people like to lie on the bed, others like to sleep on the chair. How do you do that in code? Look at the following

Class People(): def sleep(self): print(self) ) class Roommate(People): def sleep(self): print(' Sleeping on a chair... ')Copy the code

See, even sleeping on a Roommate’s chair is just one way to achieve polymorphism through inheritance. It can be done in other ways, such as this way, where the arguments to the method are superclasses.

# Different objects call the same method with the same result. fun(obj): print( obj.__len__() )Copy the code

A common method in Python

Add a few common methods for example

The standard module Random contains a function called choice that selects an element from a sequence. from random import choice x = choice(['Hello,world ! ',[1,2,'e','e',4]]) x.ount ('e') 2 __dict__ # Find which class object A belongs to.__class__ # Check whether methods or attributes exist in the object Hasattr (instance, 'methedName | attrName') # set object properties setattr (instance, 'attrName, value')Copy the code

Abstract classes in Python

About abstract classes: defines a rule (abstract method) that subclasses that inherit this class must implement abstract methods in the abstract class. Furthermore, abstract classes cannot be instantiated. The ABC module is introduced in Python to implement the definition of abstract classes, as shown in the following example:

Abstractmethod class Talker(ABC) abstract Talker class Talker(ABC) abstract Talker class Talker(ABC) @abstractmethod def talk(self): passCopy the code

This is a song about object – oriented design.

  1. To put things together, if a method uses a global variable, treat it as a class property and method
  2. Don’t let your partners get too close to each other. That’s what we call a decoupled sum.
  3. Be careful with inheritance, especially multiple inheritance.
  4. Keep it simple and keep it as short as possible.
How do you translate requirements into concrete entity classes? We can try to do that. Describe the requirements and record the nouns, verbs and adjectives. Find possible classes in nouns, possible methods in verbs, possible attributes in adjectives, and finally assign the methods and attributes found to each class. This gives us a model of the class, and then we can think about relationships between objects, inheritance or composition. Then think about the corresponding business model that can be used, after each business module is clear thinking can start programming.Copy the code

Exception handling in Python

Here’s a quick look at the exception handling mechanism in Python.

Use the keyword raise for example, raise Exception(‘ Exception MSG! ‘) but it is important to note that exceptions can only be thrown as Exceptions or subclasses of Exceptions.

Catch exceptions: We can use try… except : … finally: … Statement block to handle code that might have an exception.

try 1 / 0 except ZeroDivisionError as e: print(e) else : print('No exception will run ... ') finally : print('must be run ... ')Copy the code

Custom Exception class, define a class to inherit the Exception class.

class MyException(Exception):
    pass
Copy the code