程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

How to apply Python classes and objects

編輯:Python

Python How to apply classes and objects

This article introduces “Python How to apply classes and objects ” Knowledge about , During the operation of the actual case , Many people will encounter such difficulties , Next, let Xiaobian lead you to learn how to deal with these situations ! I hope you will read carefully , Be able to learn !

object = attribute + Method

We have already touched on the concept of encapsulation , Throw the messy data into the list , It's a package , yes Data level encapsulation ; Package common code snippets into a function , It's also a kind of encapsulation , Is a statement level encapsulation ; Now we are going to learn from , It's also an idea of encapsulation , The source of the object is to simulate the real world , Encapsulate both data and code .

For example , The tortoise is an object of the real world , It is usually described in two parts .
(1) from Static features describe : for example , Green , It has four legs , There's a shell and so on , This is a description of the static side .
(2) from Dynamic behavior describe : for example , It can climb , If you chase it , It can run , Sometimes they bite people , Sleep and so on , This is described from the aspect of behavior .

Python So is the object in , The characteristics of an object are called “ attribute ”, The behavior of an object is called “ Method ”.:

If the tortoise is written in code , It's going to be like this :

class Turtle: # Python The class name convention in begins with an uppercase letter         #  The description of a feature is called an attribute , At the code level, they are variables     color = 'green'    legs = 4    shell = True    #  Methods are actually functions , By calling these functions to do something     def climb(self):        print(' Climb forward ')    def run(self):        print(' Run forward ')    def bite(self):        print(' bite ')    def sleep(self):        print(' sleep ')

The above code defines Characteristics of the object ( attribute ) And behavior ( Method ), But it's not a complete object , These definitions are called class (Class). You need to use classes to create a real object , This object is called one of this class example (Instance), Also called Instance object (Instance Objects).
for instance , It's like a factory needs to produce a series of toys , You need to make a mold for this toy first , Then according to this mold and mass production .

So how to create a real instance object ? Create an object , Also called class instantiation , It's very simple :

#  First of all, there must be the definition of the above paragraph of class tt = Turtle()

Be careful : The class name is followed by parentheses , This is the same as calling functions . So in Python in , The class name convention starts with an uppercase letter , Functions start with lowercase letters , It's easier to distinguish . in addition , Assignment operations are not required , But if the created instance object is not assigned to a variable , This object cannot be used , Because there is no reference to this instance , Will eventually be Python The garbage collection mechanism of automatic collection .

If you want to Call methods in objects , Use the dot operator (.) that will do .


 

Now let's look at a piece of code , Let's get to the bottom of it class Class object and Instance object Three concepts :

As can be seen from this example , For instance objects c Of count Property is assigned , Equivalent to Overrides class objects C Of count attribute . As shown in the figure below , If there is no assignment override , So the reference is the class object count attribute .

It should be noted that , The properties defined in the class are Static variables , Class properties are bound to class objects , It doesn't rely on any of its instance objects .

in addition , If the name of the property is the same as the name of the method , Property will override the method

To avoid name conflicts , We should abide by some established rules :
(1) Don't try to define all conceivable features and methods in a class , It should be extended using inheritance and composition mechanisms .
(2) Name it with different parts of speech , For example, attribute names use nouns 、 The method name is a verb , And use the hump nomenclature, etc .

self What is it?

Careful readers have a way to find objects self Parameters , So this self What is it? ? If you have C++, Then it should be easy for you to take your seat according to the number ,Python Of self It's the same thing as C++ Of this The pointer .

If you haven't been exposed to any programming languages before , So simply put , If you put Classes are compared to drawings , that The object instantiated by the class is the real house . Thousands of houses can be designed according to one drawing , They all look the same , But every house has a different owner . Everyone has to find their own house , that self It is equivalent to the house number here , With self, You can easily find your own house .

Python Of self Parameters are the same thing , A class can generate countless objects , When an object method is called , Object passes its own reference to the method as the first parameter , that Python You will know which object you need to operate .

A simple example :

Public and private

General object-oriented programming languages distinguish between public and private data types , image C++ and Java They use public and private Keywords are used to declare whether the data is public or private , But in Python There are no similar keywords to decorate .

By default, the properties and methods of objects are public , You can use the dot operator directly (.) Visit

In order to implement features similar to private variables ,Python There's an internal system called name mangling( Name adaptation ) Technology , stay Python in To define a private variable, you only need to add... Before the variable name or function name “_ _” Two underscores , Then the function or variable becomes private

such , External variable names “ hide ” get up 了 , Theoretically If you want to access , From the inside

But think about the name of this technology name mangling( Name adaptation ), It is not difficult to find out that Python Just changed the name of the variable that begins with the double bottom line . actually , Use outside “_ Class name _ _ Variable name ” You can access the private variables at the beginning of the double bottom line

explain :Python The current private mechanism is actually Pseudo private ,Python Of Class has no permission control , All variables can be called externally .

Inherit

Take an example to illustrate inheritance . For example, now there is a game , Fish need to be subdivided , There are goldfish (Goldfish)、 The carp (Carp)、 salmon (Salmon) And sharks (Shark). So can we not redefine a new fish from beginning to end every time ? Because we know that the properties and methods of most fish are similar , If there is a mechanism for these similar things to be delivered automatically , So it's much more convenient . This is inheritance .

The syntax of inheritance is simple :

c l a s s class name ( By Following bearing Of class ) : . . . class Class name ( Inherited class ): \\ \quad ... class Class name ( Inherited class ):...

The inherited class is called Base class 、 Parent or superclass ; The successor is called Subclass , A subclass can inherit any properties and methods of its parent class .

for instance :

It should be noted that , If A subclass defines a method or property with the same name as the parent class , The method or property corresponding to the parent class will be automatically overridden

Next , Try to write about the goldfish mentioned at the beginning (Goldfish)、 The carp (Carp)、 salmon (Salmon) And sharks (Shark) Example .

import random as rclass Fish:    def __init__(self):        self.x = r.randint(0, 10)        self.y = r.randint(0, 10)    def move(self):        #  Here we mainly demonstrate the inheritance mechanism of class , The problem of checking the scene boundary and moving direction is not considered         #  Suppose all the fish are swimming westward         self.x -= 1        print(" My position is :", self.x, self.y)#  The goldfish class Goldfish(Fish):    pass#  The carp class Carp(Fish):    pass# salmon class Salmon(Fish):    pass#  The above three kinds of fish are all food , Direct inheritance Fish All properties and methods of the class #  The following defines sharks , In addition to inheritance Fish Class properties and methods , Also add a way to eat class Shark(Fish):    def __init__(self):        self.hungry = True    def eat(self):        if self.hungry:            print(" Eat you !")            self.hungry = False        else:            print(" Too full , I can't eat any more ~")

First run this code , Then test :

Also inherited from Fish class , Why goldfish (goldfish) Can be moved , And sharks (shark) When I move, I will report an error ?
You can see that the error message is :Shark Objects have no x attribute , This is a Because in Shark Class , Rewrote _ _init_ _() Method , But new _ _init_ _() Method does not initialize shark x Coordinates and y coordinate , So call move() The method will go wrong .
So solve this problem , as long as Rewrite in shark class _ _init_ _() Method, call the base class first Fish Of _ _init_ _() Method .

Here are two techniques that can be implemented :

  • (1) Call unbound parent class method

  • (2) Use super function

Call unbound parent class method

What is calling unbound parent methods ? for instance :

After the modification , Run it again and find that the shark can also move successfully :

What needs to be noted here is , This self It's not a superclass Fish Instance object of , It's a subclass Shark Instance object of . Therefore, unbound means that the instance object of the parent class does not need to be bound , Use the instance object of subclass instead .

Use super function

super Function can help us Automatically find the method of the base class , But also for us Into self Parameters , So you don't have to do these things :

After running, we get the same result :

multiple inheritance

besides ,Python And support multiple inheritance , It can be Inherit the properties and methods of multiple parent classes at the same time

c l a s s class name ( Father class 1 , Father class 2 , Father class 3 , . . . ) : . . . class Class name ( Parent class 1, Parent class 2, Parent class 3,...):\\ \quad ... class Class name ( Parent class 1, Parent class 2, Parent class 3,...):...

for instance :

This is the basic multiple inheritance syntax , But multiple inheritance can easily lead to code confusion , So when you're not sure you really have to use multiple inheritance , Please try to avoid using it , Because sometimes there will be unforeseen BUG.

Combine

I learned the concept of inheritance , Multiple inheritance is also mentioned , But if we have turtles now 、 fish , Now you need to define a class , It's called a pool , There should be turtles and fish in the pool . It's strange to use multiple inheritance , Because the pool and the turtle 、 Fish are different species , So how to combine them into a pool class ?
Actually in Python It's very simple , direct Put the required classes into instantiation That's all right. , This is called Combine

Run the above code first , Then test :

Structure and deconstruction

Python There are many magic methods for the object of , If your object implements one of these methods , Then this method will be Python The call , And all this is Automatically Of .

_ _init_ _(self[, …]) Construction method

Usually put _ _init_ _() Methods are called construction methods , Just instantiate an object , This method is called automatically when the object is created . When you instantiate an object, you can pass in parameters , These parameters are automatically passed in _ _init_ _() In the method , Sure By overriding this method, you can customize the initialization operation of the object .

for instance :

Some readers may ask , Sometimes it is written in the class definition _ _init_ _() Method , Sometimes it doesn't , Why is that ? Here's an example :

What needs to be noted here is ,_ _init_ _() The return value of the method must be None, It can't be anything else

therefore , It is generally rewritten when initialization is required _ _init_ _() Method . So this _ _init_ _() Method and Is not the first method to be called when instantiating an object .

_ _new_ _(cls[, …]) Method

_ _new_ _() The method is The first method called when an object is instantiated . Unlike other methods , its The first parameter is not self It's this class (cls), The other parameters are passed directly to _ _init_ _() Methodical .

_ _new_ _() Method needs Returns an instance object , Usually cls The object instantiated by this class , Of course, you can also return other objects .

_ _new_ _() Method seldom rewrites it , General yield Python Use the default scheme . however There is a case where you need to rewrite this method , Namely When inheriting an immutable type When , Its characteristics are particularly important .

_ _del_ _(self) destructor

if _ _init_ _() and _ _new_ _() If the method is the constructor of an object , that Python It also provides a destructor , called _ _del_ _() Method . When the object is about to be destroyed , This method will be called . But here's the thing , Is not del x It's equivalent to automatically calling x._ _del_ _(),_ _del_ _() Method is called when the garbage collection mechanism recycles the object . for instance :

What is binding

The concept of binding was mentioned earlier , So what is binding ?Python It strictly requires that a method must have an instance to be called , This limitation is actually Python The so-called binding concept .

Someone might try this , And discovery can also call :

however , There is a problem with this , Namely The object instantiated according to the class cannot call the function in it at all

It's actually due to Python Binding mechanism of , It's automatic here bb Object is passed in as the first parameter , That's why TypeError.

Let's do another example :

_ _dict_ _ Attributes are made up of a dictionary , There are only Properties of an instance object , Do not display class properties and special properties , The key represents the property name , The value represents the corresponding data value of the property .

Now the instance object dd There are two new attributes , And these two attributes belong to the instance object only :

Why is that? ? In fact, it's all due to self Parameters : When instance object dd To call setXY Method time , it The first parameter passed in is dd, that self.x = 4, self.y = 5 Which is equivalent to dd.x = 4, dd.y = 5, So in the instance object , Not even in class objects x and y, Because These two properties belong only to instance objects dd Of .

If you delete class instances , Instance object dd Can I call printXY Method ? The answer is yes :

“Python How to apply classes and objects ” That's all for , Thanks for reading . If you want to know more about the industry, you can pay attention to Yisu cloud website , Xiaobian will output more high-quality practical articles for you !


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved