current position:Home>Self taught Python 26 method
Self taught Python 26 method
2022-05-15 05:22:49【Gentiana wild dust dream 520】
Python Object oriented programming technology ( 3、 ... and )
List of articles
- Python Object oriented programming technology ( 3、 ... and )
- One 、 Define and use class methods
- Two 、 Construction method
- 3、 ... and 、 Method call
- Four 、 Create multiple instances
- 5、 ... and 、 Use private methods
- 6、 ... and 、 destructor
- 7、 ... and 、 Static methods and class methods
- 8、 ... and 、 Class
One 、 Define and use class methods
stay Python In the program , Keywords can be used def Define a method inside the class . After defining the methods of the class , You can make classes have certain functions . When the method of this class is called outside the class, the corresponding function can be completed , Or change the state of the class , Or achieve other purposes .
stay Python in , Class methods are defined in a way similar to other general functions , But there are three differences :
(1) Methodical The first parameter must be self, And you can't omit ;
(2) Method needs to instantiate the class , And “ Instance name . Method name ( parameter list )” Call in the form of ;
(3) You must indent one unit as a whole , Indicates that this method belongs to the content in the dry body .
For example, in the following example code , Demonstrates the process of defining and using class methods .
class Simplclass:
def info (self):
print(" The class I define :")
def mycacl (self,x,y):
return x + y
sc = Simplclass()
print(" call info Result of method :")
sc.info()
print(" call mycacl Result of method :")
print(sc.mycacl(3,4))
In the example code above , First, a method with two methods is defined info() and mycacl() Class , Then instantiate the class , And call these two methods . The function of the first method call is to directly output information , The function of the second method call is to calculate the parameters 3 and 4 And . After execution, it will output : Be careful : When defining methods , You can also declare various forms of parameters as you define functions . When a method is called , No need to provide self Parameters .
Two 、 Construction method
stay Python In the program , When defining a class, you can define a special constructor , namely __init__ () Method , Be careful init There are two lower lines before and after "__". The constructor is used to initialize the relevant data when the class is instantiated , If there are relevant parameters in this method , When instantiating, you must provide .
stay Python In language , There are many classes that tend to create objects in the form of initial states , So you will see in many classes that you define a class named __init_() Construction method of , For example, the following demo code :
def __init __(self) :
self.data = [ ]
stay Python In the program , If you define __init__ () Method , Then the instantiation operation of the class will automatically call __init__ () Method . So next, you can create a new instance :
x = MyClass ()
Construction method __init__ () There can be parameters , Parameters are determined by the construction method __init__ () Passed to the instantiation operation of the class . For example, in the following example code , Parameters through __init__ () Passed to the instantiation operation of the class :
class Complex:
def __init__(self,realpart,imagpart):
self.r = realpart
self.i = imagpart
print(" Do you know the profit of a bowl of bean curd ?")
x = Complex(0.1,2.4)
print(x.r," To ",x.i," Between ")
Output after execution :
Suppose there's a scenario , classmate “ Huo Laoer ” Our pet dog is a valuable breed , It has two unique skills of barking and sticking out the tongue . In the following example , Defines the dog class Dog, Then according to the class Dog Each instance created will store the name and age , And give the puppy a bark “wang” And stick out your tongue “shen” Skill . The code is as follows :
class Dog:
" Dog class "
def __init__(self,name,age):
" Initialization property name and agw"
self.name = name
self.age = age
def wang(self):
" Simulate a dog barking "
print(self.name.title() + " Wang Wang ")
def shen(self):
" Simulate a dog sticking out its tongue "
print(self.name.title() + " Stick out your tongue ")
In the above code , In the 1 Line defines a named Dog Class , The brackets in this class definition are empty . Then in the first 2 Line writes a document character , The functions of this class are described . In the 3 Use constructors in line code __init__ () , Whenever according to class Dog When creating a new instance ,Pyhon This method will run automatically . In this construction method __init__ () In the name of , There are two lower lines at the beginning and at the end , It's a convention , The purpose is to avoid naming conflicts with common methods in the program .
In the above method __init__ () The definition contains three formal parameters , Namely self、name and age. In the definition of this method , Among them, formal parameters self Is essential , And must precede the other parameters . Why on earth must formal parameters be included in the method definition self Well ? This is because when Python Call this __init__ () Method to create a class Dog When an instance of the , The arguments are automatically passed in self. stay Python In the program , Every method call associated with a class automatically passes arguments
self, This is a reference to the instance itself , You can enable instances to access properties and methods in classes .
When creating a class Dog When an instance of the ,Python The class is automatically called Dog Construction method in __init__ () . We're going to go through the argument direction Dog() Pass on “name" and “age”. because self It will automatically pass , So we don't need to pass it , Whenever according to class Dog When creating an instance , You only need to give the last two formal parameters (name and age) Just provide a value .
In the 5 Xing He 6 Line code , Both variables defined have prefixes self. stay Python In the program , With sef Variables prefixed with can be used by all methods in the class , And you can also access these variables through any instance of the class . Code “self.name = name” Can get stored in the formal parameter name The value in , And store it in a variable name in , The variable is then associated with the currently created instance . Code “slf.age = age”“ The effect is similar to this . stay Python In the program , Variables that can be accessed through instances are called properties .
Pass the first 7 Xing He 10 Line code , In the class Dog Two other methods are also defined in : angO) and shen() Because these methods do not require additional information , Such as “name" or “age”, So they have only one formal parameter self . In this way, the instance to be created later can access these methods , in other words ,
They all do “ bark ” and “ Stick out your tongue ”. The method in the above code Wang() and shen() It has limited functions , Just print a message that is barking or sticking out your tongue .
3、 ... and 、 Method call
Method call is to call the created method , stay Python In the program , Methods in this class can call methods in this class , You can also call global functions to implement related functions . Global functions are called in the same way as procedure oriented functions , When calling methods in this class, you should use the following format :
self. Method name ( parameter list )
stay Python When a method in this class is called in a program , The reader should note that , You should include... In the parameter list provided “self” . For example, in the following example , Demonstrates the process of calling the class's own methods and global functions in the class :
def diao(x,y):
return(abs(x),abs(y))
class Ant:
def __init__(self,x=0,y=0):
self.x = x
self.y = y
self.d_point()
def yi(self,x,y):
x,y = diao(x,y)
self.e_point(x,y)
self.d_point()
def e_point(self,x,y):
self.x += x
self.y += y
def d_point(self):
print(" The track is moving :(%d,%d)" %(self.x,self.y))
ant_a = Ant()
ant_a.yi(2,7)
ant_a.yi(-5,6)
In the example code above , First, a global function is defined diao(), Then the class is defined “Ant”, And a construction method is defined in the class , And other methods in the class are also called in the construction method d_point(). Then define the method yi() At the same time, the global function is called diao() And two methods in the class e_point() and d_point(). On the code line “ant_a=Ant()" in , Because when initializing classes Ant Class without parameters , So the default value is used after running “0,0”. Because on the line of code “ant_a.yi(2,7)” Parameters are provided in “2,7”, So the position becomes (2,7). On the code line “ant_a.yi (-5,6)” Parameters are provided in “-5,6”, So the position changes to (7, 13). After execution, it will output :
Four 、 Create multiple instances
stay Python In the program , You can think of a class as a template for creating instances . You can only create instances in classes , This class becomes meaningful . For example, in the second example of the construction method earlier in this chapter , class Dog Just a series of instructions , Give Way Python Know how to create a representation “ pet dog ” Example . Instead of creating an instance object , So nothing will be displayed after running . To make a class Dog Become meaningful , Can be based on class Dog Create more examples , Then you can use point “.” Symbolic notation to call a class Dog Any method defined in . And in Python In the program , Any number of instances can be created according to the class as required . For example, in the following example , Demonstrate the process of creating multiple instances in a class :
class Dog:
" Dog class "
def __init__(self,name,age):
" Initialization property name and agw"
self.name = name
self.age = age
def wang(self):
" Simulate a dog barking "
print(self.name.title() + " Wang Wang ")
def shen(self):
" Simulate a dog sticking out its tongue "
print(self.name.title() + " Stick out your tongue ")
my_dog = Dog(" Big dog ",6)
your_dog = Dog(" puppy ",3)
print(" The name of Huo Laoer's dog is " + my_dog.name.title() + ".")
print(" Huo Laoer's dog has " + str(my_dog.age) + " Year old !")
my_dog.wang()
print("\n Your dog's name is " + your_dog.name.title() + ".")
print(" Your dog has " + str(your_dog.age) + " Year old !")
your_dog.wang()
In the example code above , The class defined in the previous example is used Dog, In the 13 Line of code creates a name by “ Big dog ”、age by “6” My little dog , When you run this line of code ,Python Can use arguments “ Big dog ” and “6” Calling class Dog The method in __init__(). Method __init__() An instance representing a particular dog will be created , And use the values we provide to set the properties name and age. in addition , Although in the way __ init__() Does not explicitly include returmn sentence , however Python An instance representing the dog will be returned automatically . In the above code , Store this instance in a variable my_dog in .
In the first 14 A new instance is created in line of code , among name by “ puppy ”,age by “3”. The first 13 The dog instance in the line and the 14 The dog instances in the row are independent , Each has its own attributes , And be able to perform the same operation . For example, in the second 15、16、17 Line code , The instance object is output independently “my_dog" Information about . In the first 18、19、20 Line code , The instance object is output independently “your. dog” Information about , After execution, it will output :
5、 ... and 、 Use private methods
stay Python There are also... In the program “ private ” The concept of , Unlike most languages , One Python function 、 Whether a method or property is private or public , It all depends on its name . If one Python function 、 The name of a class method or property is underlined with two lines “__” Start ( Be careful , It's not the end ), So this function 、 Methods or properties are private , All other ways are public . When a private member is called inside a class , You can use some “.” Operator implementation , For example, the syntax format of calling private methods inside a class is as follows .
self.__ Method name
stay Python In the program , Private functions 、 The characteristics of a method or attribute are as follows .
● Private functions cannot be called from outside their modules .
● Private class methods cannot be called from outside their classes .
● Private properties cannot be accessed from outside their classes .
stay Python In the program , Private methods of this class cannot be called outside this class . If you want to try to call a private method ,Python Will throw a somewhat misleading exception , Claim that that method does not exist . Of course, it does exist , But it's private , So it can't be used outside the class . Strictly speaking , Private methods are accessible outside their classes , It's just not easy to deal with . stay Pyhon In the program , Nothing is really private . Inside a class , The names of private methods and properties are suddenly changed and restored , So that they appear to be unusable with their given name . For example, in the following example , Demonstrates the process of using private methods :
class Site:
def __init__(self,name,url):
self.name = name
self.__url = url
def who(self):
print(" Shop name :",self.name)
print(" website :", self.__url)
def __foo(self):
print(" This is the private method ")
def foo(self):
print(" This is a shared approach ")
self.__foo()
x = Site(" Huo Laoer tofu shop ","www.doufu")
x.who()
x.foo()
#x.__foo() # This line of code reports an error
Private methods are defined in the above code __foo, You can use... In a class . In the last line of code , Want to try calling private methods externally __foo, This is in Python Is not allowed in . After execution, it will output :
6、 ... and 、 destructor
stay Python In the program , The deconstruction method is __del__(), “del” There are two lower lines before and after “” . When using built-in methods del() When deleting objects , Will call its own destructor . In addition, when an object is called in a certain scope, , While jumping out of its scope, the destructor will also be called once , In this way, the destruct method can be used del() Free up memory . For example, in the following example , Demonstrates the process of using the deconstruction method .
class NewClass(object):
num_count = 0
def __init__(self,name):
self.name = name
NewClass.num_count += 1
print(name,NewClass.num_count)
def __del__(self):
NewClass.num_count -= 1
print("Del",self.name,NewClass.num_count)
def test():
print("aa")
aa = NewClass(" Regular customer ")
bb = NewClass(" Big customers ")
cc = NewClass(" Group customers ")
del aa
del bb
del cc
print("Over")
In the example code above ,num_count Is a global , So whenever you create an instance , Construction method __init__() It will be called ,num_count Increasing the value of the 1. When the program is finished , All instances will be destructed , Call method __del__(), Every call ,num_count Value decrement of 1. After execution, it will output :
7、 ... and 、 Static methods and class methods
stay Python In the program , The methods in the class can be divided into several types , One of the most commonly used is the example method 、 Class methods and static methods . The details are as follows .
(1) Example method : The methods in all classes used earlier in this book are instance methods , The implicit call parameter is the instance of the class .
(2) Class method : The parameters of the implicit call are the class . When defining class methods , Decorators should be used @classmethod To embellish , And there must be default parameters “cls”
(3) Static methods : There are no implied call parameters . Class methods and static methods are defined differently from instance methods , They are called in different ways . When defining static methods , You should use modifiers @staticmethod To embellish , And there are no default parameters .
Be careful : When calling class methods and static methods , Can be called directly by the class name , There is no need to instantiate the class before calling . in addition , You can also use any instance of this class to call . For example, in the following example code , Demonstrates the process of using class methods and static methods :
class Jing:
def __init__(self,x=0):
self.x = x
@staticmethod
def static_method():
print(" The static method... Is called here !")
@classmethod
def class_method(cls):
print(" Class methods are called here ")
Jing.static_method()
dm = Jing()
dm.static_method()
dm.class_method()
In the above code , In the class Jing Both static methods and class methods are defined in , Then call with the class name before instantiation , Finally, call with class instance after instantiation . After execution, it will output :
8、 ... and 、 Class
stay Python In the program , Class can define special methods , Also known as proprietary methods . Special method means that in special cases, when special grammar is used, it is determined by pyhon Called for you , Instead of calling... Directly in code ( Like the ordinary way ). For example, the construction method explained earlier in this chapter __init__() And deconstruction methods __de__ It's often See our proprietary method .
stay Python In language , The proprietary methods commonly used in class are shown in the following table .
Method name | Sketch Statement |
---|---|
__init __ | Construction method , Call... When the object is generated |
__del __ | destructor , Use... When releasing objects |
__ repr__ | Print , transformation |
__ setitem__ | Assign values according to the index |
__ getitem__ | Get values by index |
__ len__ | Get the length |
__ cmp__ | Comparison operations |
__ call__ | Function call |
__ add__ | Add operation |
__ sub__ | Subtraction operation |
__mul __ | Multiplication |
__div __ | In addition to the operation |
__ mod__ | The remainder |
__ pow__ | chengfang |
copyright notice
author[Gentiana wild dust dream 520],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/131/202205111228049805.html
The sidebar is recommended
- Build Python project in Jenkins, pychar output is normal and Jenkins output modulenotfounderror: no module named problem
- Interface request processing of Python webservice
- Download third-party libraries offline in Python
- Web automation in Python
- Importlib.exe in Python import_ Module import module
- Operation of OS Library in Python
- Some integration operations on Web pages in Python
- Python realizes the super fast window screenshot, automatically obtains the current active window and displays the screenshot
- Implementation of workstation monitoring system with Python socket
- Resume Automation - word 92
guess what you like
Django foundation -- 02 small project based on Database
Python drawing word cloud
Django foundation -- 02 small project based on Database
MNIST dataset classification based on Python
Design of FTP client server based on Python
Signing using RSA algorithm based on Python
Website backend of online book purchase function based on Python
Implementation of Tetris game based on Python greedy search
Django Foundation
Case: Python weather broadcast system, this is a rainy day
Random recommended
- Python development alert notification SMS alert
- How to configure Python environment library offline in FME
- Python: fastapi - beginner interface development
- Generate password based on fast token and fast token
- [Django CI system] use of json-20220509
- [Django CI system] if the front-end date is complete, it will be fully updated to the back-end; If the front-end date is incomplete, the date will not be updated to the back-end-20220510
- [Django CI system] echarts dataset standard writing - 20220509
- [Django CI system] obtain the current time, the first day and the last day of the month, etc. - 20220510
- wxPython wx. Correction of font class · Wx Font tutorial
- NCT youth programming proficiency level test python programming level 3 - simulation volume 2 (with answers)
- Design of personal simple blog system based on Django (with source code acquisition method)
- [Python Script] classify pictures according to their definition
- Wu Enda's classic ml class is fully upgraded! Update to Python implementation and add more intuitive visual teaching
- Six built-in functions called immortals in Python
- Some insights of pandas in machine learning
- Introduction to Python [preliminary knowledge] - programming idea
- Stay up late to tidy up! Pandas text processing Encyclopedia
- Python recursion to find values by dichotomy
- Open 3D Python Interface
- [true title 02 of Blue Bridge Cup] Python output natural number youth group analysis of true title of Blue Bridge Cup Python national competition
- Introduction to the differences between Python and Java
- Explain Python CONDA in detail
- The pycham downloaded by MAC reports an error as soon as it is opened. The downloaded Python interpreter is also the latest version
- From entry to mastery, python full stack engineers have personally taught Python core technology and practical combat for ten years
- Python is used to detect some problems of word frequency in English text.
- How to choose between excel, database and pandas (Python third-party library)?
- WxPython download has been reporting errors
- Pyside6 UIC and other tools cannot be found in the higher version of pyside6 (QT for Python 6). How to solve it?
- About Python Crawlers
- Successfully imported pandas, unable to use dataframe
- How to extract some keywords in the path with Python
- Python encountered a problem reading the file!
- When Python is packaged into exe, an error is reported when opening assertionerror: C: \ users \ Acer \ appdata \ local \ temp\_ MEI105682\distutils\core. pyc
- Eight practical "no code" features of Python
- Python meets SQL, so a useful Python third-party library appears
- 100 Python algorithm super detailed explanation: a hundred dollars and a hundred chickens
- [fundamentals of Python] Python code and so on
- When Python uses probit regression, the program statement is deleted by mistake, and then it appears_ raise_ linalgerror_ Unrecognized error of singular
- Python testing Nicholas theorem
- Accelerating parallel computing based on python (BL) 136