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

Analysis of Python object-oriented programming example

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

In this article, the editor introduces "Python object-oriented programming case analysis" in detail, with detailed contents, clear steps and proper handling of details. I hope this "Python object-oriented programming example analysis" article can help you solve your doubts.

What is object-oriented programming (class)

The process of using object-oriented (properties and methods) to code, that is, object-oriented programming.

Custom object data type is the concept of class in object-oriented.

The keyword of the class-class

The class keyword is used to declare a class, the first letter of the class name is capitalized, and in the case of multiple words, the first letter of each word is capitalized (that is, hump nomenclature). When we first learned Python, we said that we should try to avoid using hump naming, but class naming is a special case, class naming can use hump naming.

Definition and use of classes

An example of a class definition is as follows:

Class Nmae (object): # class keyword + class name (uppercase) + parentheses (fill in object in parentheses: common object in python Class for writing generic objects will have more built-in functions) + colon variable = variable value # can define the class variable def func (self): do # can also define the class function: there is a required parameter 'self' in the class function, which must be written in the first parameter bit of the class function This is the syntax provision within python # it is important to note that the properties of the class should be unified with the indentation of the function.

Examples of the use of the class are as follows:

# define an animal class; define a variable in the animal class Define a running function (attribute) class Animal (object): # define a class name = 'husky' # class variable (class attribute) def run (self): # class function: pass self as the first argument to the class function 'run ()' print (f'{self.name} can run') # 'self.name' is a class attribute If you don't add 'self.'' The class attribute will not be found; if you want to call the class attribute in the class function, you must add the 'self.' #' self' parameter to have two functions # 1. It can help us to call the class attribute # 2. The function using self is called into the class. If we have another function, we can use 'self.'' in another function. To call run function dog = Animal () # instantiation print (dog.name) # instantiate attribute call dog.run () # instantiate function call # > execution result is as follows: # > husky # > the parameter of husky can run class-self

In the class, all instance methods need to add the self parameter, and ranked first, there is only one.

The meaning of the self parameter: the method defined in the class, the first parameter self points to the instance object that calls the method, through self. Property to access the instance properties of an object

Self is a required parameter in a class function and must be placed in the first argument position

Self is an object that represents the instantiated variable itself

Self can be directly passed through the dot (.) To define a class variable such as self.name = Neo, if you define a variable in the function body, you can use self +. + variable name for assignment.

Variables in self and functions with self parameters can be called at will within any function in the class.

Variables defined in non-functions do not need to use self when timing

How to understand self parameters

Analogy

If you compare a class to a drawing for building a house

The object instantiated by the class is a real house that can live in.

According to a drawing (class), thousands of houses (instance objects) can be designed.

Each house looks similar (all have the same instance properties and methods), but they all have their own owners.

How to distinguish different houses: through the self parameter, you can ensure that the director of each house can only enter his own house (each instance object can only call its own instance properties and instance methods).

Highlight

A class can produce multiple instance objects, and when an instance object calls an instance method, the object automatically passes its own reference to the method as the first parameter.

In other words: Python automatically points the first parameter of the instance method to the object that calls the method

In this way, the Python interpreter knows which object's instance method to execute.

When you call an instance method, you do not need to manually pass a value for the first parameter

Maybe you don't quite understand. According to the attributes and methods of the two key elements of the class, let's use self to see the actual application effect:

Class Persion (object): name = None age = None def run (self): print (f'{self.name} fitness program is\ 'running\') def swim (self): print (f'{self.name} fitness program is\ 'swimming\') neo = Persion () neo.name = 'Neo'neo.run () # > the execution result is as follows: # > > Neo fitness program is' running'

Let's re-instantiate an object to see if the new instantiated object synchronizes the neo.name.

Class Persion (object): name = None age = None def run (self): print (f'{self.name} fitness program is\ 'running\') def swim (self): print (f'{self.name} fitness program is\ 'swimming\') neo = Persion () neo.name = 'Neo'neo.run () jack = Persion () jack.run () # > execution results are as follows The fitness program of Neo is' running'# > None's fitness program is' running'

From the output, we can see that the value of the corresponding name of the modified neo instantiated object only acts on its own instance, while the Persion class and the new jack instantiated object are not affected.

So even if we instantiate with a new object, we still need a new instantiated object to modify the properties of the class to achieve the effect we want. In fact, it is easy to understand that they are all human, but the individualization of each person is different. So after they have common human attributes (name,age), they can also customize their own attributes.

Now that our Persion class defines two properties, 'name'' and 'age', what if we add another property? Oh, actually, it's possible. Now let's add a custom attribute for 'Jack' and give it a try.

Class Persion (object): name = None age = None def run (self): print (f'{self.name} fitness program is\ 'running\') def swim (self): print (f'{self.name} fitness program is\ 'swimming\') neo = Persion () neo.name = 'Neo'neo.run () jack = Persion () jack.top = 180print ('\ 'Jack\') Jack.top) # > execution results are as follows # > Neo's fitness program is' running'# > 'Jack' 's height is 180print ('\ 'Neo\' height is', neo.top) # > execution results are as follows: # > AttributeError: 'Persion' object has no attribute' top'

From the custom properties of jack.top and neo.top above, we found three things.

1. Instantiated objects can customize properties

two。 The properties defined by each instantiated object are not common to other instantiated objects.

After instantiating the object, the 3.Persion class still has only two properties of its own (name and age). The custom properties of the instantiated object only work on itself and do not affect the class.

Analysis and Summary of self

To tell you the truth, when I first came into contact with self in Python, it was also foggy and foggy for me. Here is a summary. I hope it will be helpful to the children's shoes which are surrounded by fog and fog in the same way.

Self in Python represents an example of a class; self is a must when defining methods for a class, although you don't have to pass in the corresponding parameters when calling.

Self in Python makes sense only if it is specific to the class.

Self can only be used in methods of the python class.

Specific examples are as follows:

Attribute

About attribute-1: if the variable is defined under the class rather than under the class's method, then the variable is both a property of the class and a property of the class instance.

Class Cat (object): eyes = 'have two eyes' legs = 'have four legs' tail = 'have a tail' dragonLi = Cat () dragonLi.name = 'civet cat' dragonLi_eyes = dragonLi.eyesdragonLi_legs = dragonLi.tailprint ('cat' + Cat.eyes, Cat.legs, Cat.tail) print (dragonLi.name, dragonLi_eyes, dragonLi_legs DragonLi_tail) # > the execution result is as follows: the cat has two eyes, four legs and one tail # > the civet cat has two eyes, four legs and one tail

About attribute-2: if the variable is defined under the method of the class, if self is added, then the variable is the property of the class instance, not the property of the class; without self, this variable is only the local variable of the method, neither the property of the class nor the property of the class instance.

Class Cat (object): eyes = 'have two eyes' legs = 'have four legs' tail = 'have a tail' def _ _ init__ (self): # for more information about _ _ init__ () in the 'class constructor' below self.color_01 = 'yellowish brown' color_02 = 'black brown' DragonLi = Cat () dragonLi_color_01 = dragonLi.color_01print ('civet cats have two coat colors One is as follows:', dragonLi_color_01) # > the execution result is as follows: yellowish brown dragonLi_color_02 = dragonLi.color_02print ('civet cat has two fur colors, the other is:', dragonLi_color_02) # > AttributeError: 'Cat' object has no attribute' color_02'.

Method

About method 1: if self is added to define a function in a class, the function is the method of the class instance, not the method of the class.

Class Cat (object): def eat (self): print ('love fish') dragonLi = Cat () dragonLi.eat () # > execution result is as follows: # > favorite fish Cat.cat () # > execution result is as follows: # > TypeError: Cat.eat () missing 1 required positional argument: 'self'

About method 2: if you define a function in a class without adding self, then the function is just the method of the class, not the method of the class instance.

Class Cat (object): def eat (): print ('love fish') Cat.eat () # > execution result is as follows: # > favorite fish dragonLi = Cat () dragonLi.eat () # > execution result is as follows: # > TypeError: Cat.eat () takes 0 positional arguments but 1 was given

Summary

Attributes:

If the variable is defined under the class rather than under the class's method, then the variable is both a property of the class and a property of the class instance.

If the variable is defined under the method of the class, if self is added, then the variable is the property of the class instance, not the property of the class; without self, this variable is only a local variable of the method, neither a property of the class nor a property of the instance of the class.

Methods:

If self is added to define a function in a class, the function is the method of the instance of the class, not the method of the class.

If you define a function in a class without self, then the function is just a method of the class, not a method of an instance of the class.

Constructor of class

Earlier, we learned about the creation of the class, the properties of the class, and how to use the class function. Now let's look at the constructor of the class.

What is the constructor of a class? The-> constructor is a default function in a class, and by defining it, you can pass parameters into the class while the class is instantiated. (similar to passing some parameters when the function is executed)

The method of creating the constructor

Important: the constructor is still defined in the class

Def _ _ init__ (self, a, b) # def keyword + _ _ init__ + parentheses (the first one passed in parentheses is still self, followed by the parameter you want to instantiate) self.a = a # in the constructor, bind the parameter in self and bind the variable through self You can call self.b = b in each function of the class

The usage of the constructor is as follows:

Class Test (object): def _ _ init__ (self, a): # _ _ init__ constructor must be written in the first This is a good programming specification self.a = a def run (self): print (self.a) test = Test (1) test.run () # > the execution result is as follows: # > > 1test_02 = Test ('Hello') test_02.run () # > execution result is as follows: # > Hello

Next, we use the constructor to modify the Cat class we created earlier.

Class Cat (object): def _ init__ (self, eyes, legs, tail, color=' yellowish brown'): self.eyes = eyes self.legs = legs self.tail = tail self.color = color def show_cat (self): self.work = 'catch mice' print ('cat's common attributes are', self.eyes, self.legs, self.tail) dragonLi = Cat ('2 eyes','4 legs' '1 tail') dragonLi.show_cat () # > the execution result is as follows: # > the common attributes of cats are 2 eyes, 4 legs and 1 tail yellowish brown dragonLi.name = 'civet cat' dragonLi.color = 'tiger spot' print (dragonLi.name, dragonLi.eyes, dragonLi.legs, dragonLi.tail, dragonLi.color) DragonLi.work) # > execution results are as follows: 2 eyes, 4 legs, 1 tail, tiger spotted mice about the life cycle of the object.

Note: the lifecycle of the object here refers to the instantiated object.

As we mentioned earlier, when a variable is not in use, it is cleaned up by the memory butler. Next let's take a look at the life of a variable, from emergence to demise. The reason why this chapter is inserted here to introduce the life cycle of objects, but also in order to better understand objects, so as to better use them.

The deep copy and shallow copy we learned before, the shallow copy is to create a new memory address, and the deep copy is to use the variables that have been determined before.

By understanding the life cycle of an object, we can weigh whether to terminate an object or continue to use them.

We instantiate an object through the constructor, and the life cycle of an object begins. At this time, the memory butler finds that the addition of an object will assign a memory address to the instantiated object (that is, the instantiated object's home in memory).

Next we can manipulate the object and call its built-in functions and functions. When we don't use this object, there are usually two situations.

The first is that there is no variable to bind the value in this memory block, for example, when the default value of one of our variables is called by a function, the variable has a new value, and the original default value of the variable is no longer assigned to the variable.

The second is when we have finished executing all the programs, that is, the code has been executed to the last line. When the Python interpreter finds that all the business has been processed, the script will stop processing and release all the objects in the script. To release all objects is to tell the memory butler, and the memory housekeeper will automatically process the memory addresses of these objects.

The unified representation of the above two cases is that these objects are no longer used, and the built-in function _ _ del__ (two underscores) in each object is called to tell the memory housekeeper to release the corresponding block of memory from memory. This is the life cycle of the entire object.

Whether it's strings, numbers, lists, tuples, dictionaries, collections, or even Boolean and null types, we know that everything in Python is an object, so they also exist and die according to this law.

Memory management in Python is done automatically, so we don't need to deal with it specifically.

There is no need for us to write and define the _ _ del__ function. When we instantiate an object, it exists by default and has the ability to automatically notify the memory housekeeper to clean up the memory. This is also one of the characteristics of Python.

After reading this, the article "Python object-oriented programming example Analysis" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, you are welcome to follow 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

Development

Wechat

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

12
Report