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

Python function and object-oriented example Analysis

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces "python function and object-oriented case analysis". In daily operation, I believe that many people have doubts about python function and object-oriented case analysis. I have consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts of "python function and object-oriented case analysis". Next, please follow the editor to study!

Function

In python, everything is an object, and functions are no exception.

In the C++ or Java you learned earlier, you can find that the return value of a function is either empty or of some data type, but in python, the return value can be any object, including a function.

Function parameter

There are many kinds of parameters of the function, mainly including:

1. Position parameter (positional argument): it is the most common x, y, etc.

Default parameter (default argument): given a default value, the user can also pass in arguments to adjust.

Def func (x, yellow3): print (Xeroy) func (1) # 4func (1666) # 667

3. Variable parameters (variable argument): there is no limit to the number of input parameters, and is automatically saved as a tuple after input.

1.*args is a variable parameter, and args receives a tuple

Def printinfo (arg1, * args): print (arg1) print (args, type (args)) printinfo (10) # there is only one parameter, and there is no. # 1 parameter () printinfo (70, 60, 50) # all other parameters are passed to the variable parameter # 7 parameters (60, 50) except those that match the arg1 position.

4. Keyword parameter (keyword argument): does not limit the number and naming of keywords, and is automatically saved in the form of a dictionary.

1.**kw is the keyword parameter, and kw receives a dict

Def printinfo (arg1, * args): print (arg1) print (args, type (args)) printinfo (10) # there is only one parameter, and there is no. # 1 parameter () printinfo (70, 60, 50) # all other parameters are passed to the variable parameter # 7 parameters (60, 50) except those that match the arg1 position.

5. Named keyword parameter (name keyword argument)

1. The purpose of naming keyword parameters is to limit the parameter names that callers can pass in, or to provide default values.

two。 Unlike keyword parameters, the names and values of keyword parameters are arbitrary and can be matched later, while naming keywords can only accept a given keyword as a parameter. Define named keyword parameters

3. Don't forget to write the delimiter *, otherwise the position parameter is defined and the keyword parameter must be given the parameter name when calling the function.

Def person (name, *, age, height=1.90): print (f'{name} this year {age}, height {height:.2f} m') person ('Zhang San', age=18, height=1.80) # Zhang San is 18 years old, height 1.80mperson ('Li Si', age=18) # Li Si is 18 years old, height 1.90mperson ('Wang Wu') # TypeError, need to pass a given keyword

6. Parameter combination

When defining functions in Python, all of the above five parameters can be used, but a maximum of four can be used, and pay attention to the order:

1. Position parameters, default parameters, variable parameters and keyword parameters.

two。 Position parameters, default parameters, named keyword parameters and keyword parameters.

Variable scope

In python programs, variables in different locations have different scopes.

A variable defined inside a function has a local scope, which is called a local variable.

A variable defined outside a function has a global scope, which is called a global variable.

Local variables can only be accessed within the function in which they are declared, while global variables can be accessed throughout the program.

It is important to note that:

When a local variable tries to access a global variable, be sure to declare global.

When local variables conflict with global variable names, the program will give priority to local variables.

Embedded functions and closures

An embedded function defines an inner function within an outer function.

Def outer (): print ('outer function is called here') def inner (): print ('inner function is called here') inner () # this function can only be called inside the outer function outer () # outer function is called here # inner function is called here

Closure is an important grammatical structure, which is similar to embedded function in structure, except that the return value of outer function of closure is a function.

If an inner function refers to a variable with an outer non-global scope, then the inner function is considered a closure.

Closures allow you to access variables with an outer non-global scope, which is called a closure scope.

Def funX (x): def funY (y): print ('use funY (y)') return x * y return funYi = funX (8) print (type (I)) # print (I (5)) # 40

Notice that in the above code, the outer non-global scope variable x. FunY is used in the inner function.

Similarly, the function scope nested within the function also requires special attention. If we need to modify the variables in the closure, we need to use the nonlocal keyword.

Num = 999def outer (): num = 10 def inner (): the nonlocal num # nonlocal keyword declares the expression of num = 100print (num = {num}'in f'inner) inner () print (num = {num}'in f'outer) outer () # inner num = num = 100print (num = {num}'in f 'global) # global num = 999lambda expression

Lambda needs to pay attention to:

Anonymous functions do not have return, and the expression itself is the return value.

Anonymous functions have their own namespace and cannot access outside the parameter list or global variables.

Anonymous functions are mainly suitable for higher-order functions in functional programming (functions do not affect anything other than functions). For example, map mapping and filter filtering, of course, can also be used in your own custom functions.

Odd = lambda x: X% 2 = = 1templist = filter (odd, [1,2,3,4,5,6,7,8,9]) print (list (templist)) # [1,3,5,7,9] M1 = map (lambda x: X * * 2, [1,2,3,4,5] print (list (M1)) # [1,4,9,16,25] object-oriented characteristics

Object-oriented must understand three major features:

Encapsulation: encapsulate objective things into abstract classes, let data and methods be manipulated by trusted classes or objects, and hide part of the information.

Inheritance: subclasses automatically share the properties and methods of the parent class.

It is generally believed that a class is a subclass of itself

You can use issubclass (B, A) to see if B is a subclass of A.

Python also supports multiple inheritance, but it complicates the overall hierarchy of the class, so it is not recommended.

Polymorphism: calls to the same method will get different results due to different objects.

The necessary conditions are inheritance and method rewriting.

Classes, class objects, and instance objects

Class: refers to the definition of a class

Class object: when creating a class, there is only one class object in a space opened up in memory.

Instance objects: there can be more than one object created by instantiating a class.

Class properties and object properties

Class attributes: within the class definition, the variables defined outside the class methods are called class attributes, which belong to class objects and can be shared by multiple instantiated objects, just as we all have a home with the name China.

Object properties: object properties are directly related to the specific object instances created, and do not share properties with each other, just as my wife is only mine.

Class A (): a = 0 # class attribute def _ _ init__ (self, xx): A. a = xx # using the class attribute can be passed through (class name. Class attribute) call.

There are some ways to manipulate properties:

Use hasattr (object, name) to determine whether an object contains corresponding properties or methods.

Use getattr (object, name) to get a property or method.

Use setattr (object, name, value) to modify property values or create new properties and values.

Use delattr (object, name) to delete attributes.

Class A (object): name = 'Zhang San' def set (self, a, b): X = an a = b = x print (a, b) a = A () print (hasattr (a, 'name')) # determine whether there is a name attribute Trueprint (hasattr (a,' set')) # determine whether there is a set method Truex = getattr (a 'name') # get attribute value print (x) # Zhang San c = getattr (a,' set') # acquisition method c (a, 'set') # 2 1 Private

Private properties and methods only need to be named with two underscores "_".

Private properties and private methods are more secure than public properties and public methods. By definition, the properties and methods that need to be protected are encapsulated as private, which can prevent direct external calls, but must be called by instantiated object methods or class methods, so as to improve security.

But private in python is pseudo-private, that is, you can use class names, access private properties through object._className__attrName, and access private methods with object._className__func ().

Class JustCounter: _ _ secretCount = 0 # private variable publicCount = 0 # public variable def count (self): self.__secretCount + = 1 self.publicCount + = 1print (self.__secretCount) counter = JustCounter () counter.count () # 1print (counter.publicCount) # "Special methods can still access print (counter._JustCounter__secretCount) #" direct access will report an error .print (counter.__secretCount)

You should pay attention to the fact that the instance can add properties by using the point directly.

Class B: def func (self): print ('call the func method') b = B () print (b. Calling the func method) # View the attribute {} b.name = 'Zhang San' b.age = 18print (b. Calling the func method) # View the attribute {'name':' Zhang San' 'age': 18} b1 = B () print (b1. Magic magic methods basic magic methods

Magic methods are basically special methods that are surrounded by underscores. Compared with ordinary methods, it can be called automatically at the appropriate time. The first parameter is usually cls "class method" or self "instance method".

_ _ init__ (self [,...]) Constructor, the initialization method that is called when an instance is created.

_ _ new__ (cls [,...]) The first method called when an object is instantiated calls _ _ new__. before calling _ _ init__ initialization

Note that the return value of _ _ new__ must be an instance of the current class, otherwise _ _ init__ initialization will not be called.

It mainly provides a way to customize the instantiation process of this class when inheriting some immutable class (such as int, str, tuple).

_ _ del__ (self) destructor, a method called when an object is about to be reclaimed by the system.

_ _ str__ (self): triggers _ _ str__. when you print an object, format it with% s, or use str to override the data type

_ _ repr__ (self) is a backup for _ _ str__ (self). The situation is similar, but customization is often more accurate and is mainly used for debugging.

Arithmetic operator

Ordinary calculation cannot be carried out in an object and needs to be customized.

_ _ add__ (self, other) defines the behavior of addition: +

_ _ sub__ (self, other) defines the behavior of subtraction:-

_ _ mul__ (self, other) defines the behavior of multiplication: *

_ _ truediv__ (self, other) defines the behavior of true division: /

_ _ floordiv__ (self, other) defines the behavior of integer division: / /

_ _ mod__ (self, other) defines the behavior of the modularization algorithm:%

_ _ divmod__ (self, other) defines the behavior when called by divmod ()

Divmod (a, b) combines the result of divisor and remainder operation to return a tuple containing quotient and remainder (a / b, a% b).

_ _ pow__ (self, other [, module]) defines the behavior when called by power () or * * operation

_ _ lshift__ (self, other) defines the behavior of bitwise left shift:

_ _ and__ (self, other) defines bitwise and operational behavior: &

_ _ xor__ (self, other) defines the behavior of bitwise XOR operations: ^

_ _ or__ (self, other) defines the behavior of bitwise or operation: |

There is also a corresponding inverse operator, which can be preceded by r, such as _ _ rsub__. For the corresponding incremental assignment operator, you can add I before it, such as _ _ isub__.

Attribute access

_ _ getattr__ (self, name): defines the behavior when a user tries to get an attribute that does not exist.

_ _ getattribute__ (self, name): defines the behavior when the property of the class is accessed (call the method first to see if the property exists, and then call _ _ getattr__ if it does not exist).

_ _ setattr__ (self, name, value): defines the behavior when a property is set.

_ _ delattr__ (self, name): defines the behavior when an attribute is deleted.

Descriptor

A descriptor is a property that assigns an instance of a particular type of class to another.

_ _ get__ (self, instance, owner): used to access the property, which returns the value of the property.

_ _ set__ (self, instance, value): will be called in the property assignment operation and nothing will be returned.

_ _ del__ (self, instance): controls the deletion operation and returns nothing.

Iterator and generator iterator

Iteration is one of the most powerful features of Python and is a way to access collection elements.

An iterator is an object that remembers the location of the traversal.

The iterator object is accessed from the first element of the collection until all elements are accessed.

Iterators can only move forward, not backward.

Strings, lists, or tuple objects can be used to create iterators.

There are two basic methods for iterators: iter () and next ():

The iter (object) function is used to generate iterators.

Next (iterator [, default]) returns the next item of the iterator. Returns the default value when the element is empty. If not, a StopIteration exception is triggered. Used in tuple deduction and next, but the following generator.

Using a class as an iterator requires the implementation of two magic methods _ _ iter__ () and _ _ next__ () in the class.

_ _ iter__ (self) defines the behavior of the elements in the iteration container and returns a special iterator object that implements the _ _ next__ () method and marks the completion of the iteration with a StopIteration exception.

_ _ next__ () returns the next iterator object.

The StopIteration exception is used to mark the completion of the iteration to prevent the occurrence of an infinite loop. In the _ _ next__ () method, we can set the StopIteration exception to be triggered after the specified number of loops to end the iteration.

Class Fibs: def _ init__ (self, Niss10): self.a = 0 self.b = 1 self.n = n def _ iter__ (self): return self def _ next__ (self): self.a, self.b = self.b Self.a + self.b if self.a > self.n: raise StopIteration return self.afibs = Fibs for each in fibs: print (each, end='') # 1 1 2 3 5 8 13 21 34 55 89 generator

In Python, a function that uses yield is called a generator.

Unlike ordinary functions, a generator is a function that returns an iterator and can only be used for iterative operations. It is easier to understand that a generator is an iterator.

In the process of calling the generator to run, every time yield is encountered, the function pauses and saves all the current running information, returns the value of yield, and continues to run from the current position the next time the next () method is executed.

Call a generator function and return an iterator object.

Def libs (n): a = 0b = 1 while True: a, b = b, a + b if a > n: return yield afor each in libs: print (each, end='') # 1 1 2 3 5 8 13 21 34 55 89, the study on "python function and object-oriented instance Analysis" is over. I hope to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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