closure
1. Closure
# def outer(m): # External function, m is the formal parameter # def inner(n): # Internal function, n is a formal parameter # Print ('value in inner function: ', m+n) # # # The return value of an external function is a reference to an internal function # return inner # Call external functions # print(outer(20)) # Print out the address of the internal function < function outer. < locals >. Inner at 0x0000018fdc2d6828 > # The first way to write: # ot = outer(20) # ot(30) # The second way to write: # outer(10)(90)
2. Function reference
# a = 10 # The address of the integer 10 is saved in a # print(a) def test(): print('This is test function') # print(test) # < function test at 0x0000021328ba6828 > function address # Call function # test() # Reference function # te = test # print(te) # Calling functions by reference # te()
If there is a pair of parentheses after the function name, it is equivalent to calling the function;
If there are no parentheses, it is equivalent to just the name of a function, which stores the reference of the location of the function
3. Each time the inner function is opened, the same closure variable is used
def outer(m): # External function print('out Value in function:', m) def inner(n): # Inner function print('inner Value in function:', n) return m+n # Return the value of m+n in the inner function return inner # Call the external function and pass the value of 10 to the outer function ot = outer(10) # Call the inner function for the first time and pass the value of 20 to the inner function print(ot(20)) # Call the inner function for the second time and pass the value of 30 to the inner function print(ot(30)) # In the process of using closures, once the outer function is called, the reference of the inner function is returned # Although the inner function is called every time. A function will be opened and die after execution, but there is only one closure variable. Each time the function is opened, the same closure variable is used # Second: # outer(10)(20)
Decorator
1. Decorator: add additional functions
# def wrapper(func, fn): # For external functions, func is a formal parameter, but the value passed in is the decorated function name: test # def inner(): # Inner function # print('login or not: already logged in ') # func() # func is actually test. func() is equivalent to calling test() # fn() # # return inner # # Decorated function # def test(): # print('comment: like ~ ') # # def test3(): # print('tweet: I learned about decorators today, and I feel very Naisi ~ ') # First: # Decorating functions with decorators # wr = wrapper(test, test3) # # Call the inner function in the decorator # wr() # Second: use the form of grammar sugar # Write directly: @ decorator name and put it on the head of the function to be decorated # @wrapper # # Decorated function # def test2(): # print('forward: This is fun ') # @wrapper # def test3(): # print('tweet: I learned about decorators today, and I feel very Naisi ~ ') # # test2() # test3()
2. The decorated function has parameters
# def outer(fn): # def inner(c, d): # c. D is the parameter in the inner function # print(f'{c}, {d} is the value' in the inner function) # fn(c, d) # fn() is exam() # return inner # @outer # # Decorated function # def exam(a, b): # print('nine songs one meter eight ') # print(f'{a}, {b} is the value' in the exam function) # exam(1, 2) # ot = outer(exam) # ot(1, 2)
3. The decorated function has variable parameters * args **kwargs
# def funa(hanshu): # def inner(*args, **kwargs): # print('Start executing decorated function! ') # hanshu(*args, **kwargs) # print('execution completed ') # # return inner # # # Decorated function # def test(*args, **kwargs): # print(args) # print(kwargs) # # fa = funa(test) # # fa('Life like water ',' Pumpkin Baby ',' Xiaobai ', name =' cappuccino ')
4. Multiple trimmers
First decorator
def maketest1(fn): def inner(): return 'I am a great fairy ' + fn() + ' Heart less' return inner
Second decorator
def maketest2(fn): def inner2(): return 'Take Le home ' + fn() + ' small amount' return inner2
Decorated function 1:
@maketest1 def test1(): return 'Stay and make up lessons'
Decorated function 2:
@maketest2 def test2(): return 'I'm going to change my name'
Decorated function 3:
@maketest1 # 'I am a great immortal' + fn() + 'Xinshao' - 'I am a great immortal' + 'Bring Music Home' + 'there are no legends in the Jianghu' + 'small amount' + 'Xinshao' @maketest2 # 'Take Le home '+ fn() +' small amount '-' take Le home '+' there are no legends in the Jianghu '+' small amount ' def test3(): return 'There are no legends in the Jianghu' # print(test1()) # print(test2()) print(test3())
The decoration process of multiple decorators. The decorator closest to the function is decorated first, and then the outer decorator is decorated. The decoration process is from inside to outside
object-oriented
1. Classes and objects
Class: a class of things with the same attributes and functions.
Object: it is the concrete expression of class and the core of object-oriented programming
Class: abstract person, object: real person
Moon Cake
Class - moon cake
Object - the moon cake I'm eating
2. Class - class
2.1 writing method of definition class: class name hump naming method, initial capital
# class name: # pass
2.2 three elements
Class name, attribute (characteristic description of object), method (behavior of object)
give an example:
Class name: human attributes: blonde hair, wearing glasses method: eating and speaking
# class Human: # hair = 'gold' # Class properties # Add, delete, modify and query a single attribute in a class, and operate through universal points # print(Human.hair) # see # Human.hair = 'black' # modify # # print(Human.hair) # Human.name = 'Bill Gates' # increase # del Human.hair # delete # print(Human.hair)
3. Add () to the object class name. This is an instantiation process, and an object will be instantiated
# Format of instantiated object: object name = class name () # Instance method: called by object, with at least one self parameter; When the instance method is executed, the object calling the method is automatically assigned to self class Person: name = 'jiuge' # Class properties def speak(self): # Example method print('In the instance method self: ', self) # self represents the object of the current calling method. print('Nine songs are talking') # Instantiated object object name = class name () p1 = Person() # Print the instantiated object and display the address of the object in memory print('First instantiated object:', p1) # Object calls methods / properties in a class p1.speak() # print(p1.name) p2 = Person() print('Second instantiated object:', p2) p2.speak()
Summary:
A class can instantiate multiple objects
Self is the first parameter in the instance method, and self represents the object itself
init and del
1. Instance attribute - self. Attribute name
# class A: # name = 'jiuge' # Class properties # # def work(self): # The instance method self represents the instance object itself # print('This is the instance method ') # print(f'What is the age of Jiuge{self.age}') # self.age instance properties
Instantiate object
# Object operates on a single attribute in an object # a = A() # a.age = 18 # Modify instance properties # a.job = 'python' # Add instance properties # print(a.job) # a.work()
2. Construction method
__ init__ Method: usually used for attribute initialization or assignment; It will be called automatically when instantiating
# class Test # def __init__(self): # print('This is init ') # # te = Test()
# Version 1: # class Hero: # Hero class # def __init__(self): # self.name = 'Li Bai' # Instance properties # self.hp = 500 # Life value # self.at = 280 # aggressivity # # # def move(self): # Example method # print(f'{self.name} is moving') # # def attcak(self): # Print (the health value of F '{self. Name} is {self.hp}, which sends out a green lotus sword song {self.at}') # # # Instantiate object # hero = Hero() # hero.move() # hero.attcak() # Version 2: # class Hero: # Hero class # def __init__(self, name, hp, at): # self.name = name # Instance properties # self.hp = hp # Life value # self.at = at # aggressivity # # # def move(self): # Example method # print(f'{self.name} is moving') # # def attcak(self): # Print (the health value of F '{self. Name} is {self.hp}, which sends out a move {self.at}') # # # Instantiate object # hero = Hero('li Bai ', 200, 100) # # hero.move() # hero.attcak() # # hero2 = Hero('pig man ', 100, 50) # hero2.move() # hero2.attcak()
Summary:
Class attribute, instance attribute
1. Class attribute belongs to class, and instance attribute belongs to object
2. Only one copy of class attribute is saved in memory, and one copy of instance object is saved in each object
3. Class attribute, which can be accessed by class and instance object; Instance property, class cannot be accessed, instance object can be accessed
# class A: # num = 10 # Class properties # def __init__(self, name): # self.name = name # Instance properties # # def test(self): # Example method # print(f 'I am {self.name}') # # # print('first instantiation object ----- ') # a = A('so love will disappear, right ') # a.test() # print(A.num) # View class properties by class name # # print(a.num) # Viewing class properties through objects # # # print(A.name) # View instance properties by class name (error report) # # print(a.name) # Viewing instance properties through objects # # print('second instantiation object ----- ') # a1 = A('nine songs') # a1.test() # print(A.num)
3. Deconstruction method – del
When an object is deleted, the interpreter calls the del method by default
# class Person: # def __init__(self): # print('I am the init method ') # # def __del__(self): # print('destroyed ') # # p = Person() # print('This is the last sentence ') # During normal operation, the del method will not be called, and "this is the last sentence" will be printed. After the object execution is completed, the system will automatically execute the del method
class Person:
def init(self):
print('I am the init method ')
def __del__(self): print('Destroyed')
p = Person()
del p # delete objects
print('This is the last sentence ')
When the del judgment statement is executed, the memory is immediately recycled and the del method of the object itself will be called
Private rights
1. Object oriented review
# class Test: # thing = 'attend class;class begins' # Class properties # # def __init__(self, name): # init initialization # print('This is init') # When creating an object, the init method will be called automatically # self.name = name # Instance properties # # def speak(self): # Example method # print(f'{self.name} is lecturing')
# Instantiated object object name = class name () # te = Test('small ') # te.speak() # print(te.thing) # print(Test.thing) # print(te.name) # Access instance properties through objects # print(Test.name) # Cannot access
2. Packaging
Category 2.1 - gunny bag, which is a kind of package in itself
Encapsulate the properties and methods into an abstract class. The external world uses the class to create objects and let the objects call methods
2.2 private is defined in the class, which is only used inside the class and cannot be accessed outside
Private permissions: precede the property name and method name with two underscores_
# class Person: # name = 'jiuge' # Class properties # __age = 18 # Private property # # def funa(self): # Example method # print('Access class attribute in instance method ', Person.name) # print('Access private property in instance method ', person. _age) # # # pe = Person() # print(pe.name) # # Private attribute: external cannot be accessed directly # # The first: understand, but it's best not to do so # # _ Class name__ Private property name # # print(pe._Person__age) # # # Second: access inside the class # pe.funa()
2.3 private attributes and methods
# _ xx: start with a single underscore, declare private properties / methods, and class objects and subclasses can be accessed # __ xx: it starts with a double underscore, private permission, and cannot be accessed directly from the outside # class Person: # name = 'jiuge' # Class properties # _sex = 'female' # Private attribute (single underline) # __age = 18 # Private attribute (double underline) # # pn = Person() # print(pn._sex) # print(pn.__age) # report errors
Private method
class Human: def __play(self): # Private method print('play with the smarthphone') def funb(self): # Example method print('This is the instance method') # Human.__play(self) # Calling private methods in instance methods self.__play() ha = Human() ha.funb()
Single inheritance
1. Succession
Inheritance enables a subclass to have all the properties and methods of the parent class
Inheritance is divided into single inheritance and multi inheritance
Syntax:
Class class name (parent class name)
Subclasses can inherit all the properties and methods of the parent class. Even if they don't have them, they can use the properties of the parent class
1.1 single inheritance
# class Animal: # Animals - parent # def eat(self): # print('--- eat --') # # def sleep(self): # print('--- sleep --') # # # class Pig(Animal): # Pigs - subclasses # pass # placeholder # # class Dog(Animal): # Dogs - subclasses # pass # # dog = Dog() # dog.eat() # dog.sleep()
1.2 transitivity of inheritance
# Class A/B/C Class C (subclass) inherits from class B (parent class), class B (subclass) inherits from Class A (parent class), and class C has the properties and methods of class A/B # A subclass has all the properties and methods in the parent class and the parent class of the parent class # class A: # Parent class of parent class --- grandpa # def eat(self): # print('--- eat --') # # def sleep(self): # print('--- sleep --') # # # class B(A): # Parent - Dad # def study(self): # print('--- learn -') # # # class C(B): # Subclass - son # pass # # c = C() # c.study() # c.eat()
2. Rewrite
2.1 override parent class method: define a method with the same name as the parent class in the subclass, which will call the method overridden by the subclass
# class Person: # Parent class # def work(self): # print('accept the test of society ') # # # class Son(Person): # Subclass # def work(self): # print('accept the beating of society ') # # son = Son() # son.work()
2.2 extend the parent class method: inherit the method of the parent class, and the child class can add its own functions
Implementation method:
1. Parent class name. Method name (self)
# class Person: # Parent class # def work(self): # print('accept the test of society ') # # # class Son(Person): # Subclass # def work(self): # Person.work(self) # print('but it was later found that he was beaten by the society ') # print(123) # # son = Son() # son.work()
2.super(). Parent class method name ()
Super in python is a special class. super() is an object created with super class. You can call the methods in the parent class
# class Animal(): # Parent class # def __init__(self, name): # self.name = name # # def bark(self): # print(f'{self.name} is calling') # # def paly(self): # print('can play ') # # class Dog(Animal): # Subclass # def bark(self): # # super().bark() # super().paly() # You can call other methods in the parent class # print(f'{self.name} barking') # # dog = Dog('husky ') # dog.bark() # 3. New class writing method: there is no difference between the three writing methods. class A(object) is recommended: # class A: # class A(): # class A(object):