Python of AI training camp

The main contents of this paper: functions, Lambda expressions, classes and objects, magic methods. 1, Functions ...
1.1 definition of function
1.2 function call
1.3 function document
1.4 function parameters
1.5 return value of function
1.6 variable scope
2.1 definition of anonymous function
2.2 application of anonymous functions
In addition to Python built-in functions, we can also define high-order functions ourselves.
3.1 object = attribute + method
3.2 what is self
3.3 Python's magic method
3.4 public and private
3.5 succession
3.6 combination
3.7 class, class object and instance object
3.8 what is binding
3.9 some related built-in functions
4.1 basic magic methods
The main contents of this paper: functions, Lambda expressions, classes and objects, magic methods.
1, Functions

1.1 definition of function

Remember "everything is an object" in Python? Python regards functions as objects, and can return from another function to build higher-order functions. For example, the parameter is a function and the return value is a function.

First, let's introduce the definition of function.

  • The function starts with the def keyword, followed by the function name and parentheses ().
  • The code executed by the function starts with a colon and is indented.
  • Return [expression] ends the function and optionally returns a value to the caller. A return without an expression is equivalent to returning None.
def functionname (parameters): "Function document string" functionsuite return [expression]

1.2 function call

def printme(str): print(str) printme("I want to call a user-defined function!") # I want to call user-defined functions! printme("Call the same function again") # Call the same function again temp = printme('hello') # hello print(temp) # None

1.3 function document

def MyFirstFunction(name): "During function definition name It's a formal parameter" # Because Ta is only a form, it means that it occupies a parameter position print('Passed inIt's called an argument because Ta Is the specific parameter value!'.format(name)) MyFirstFunction('Old horse's procedural life') # The program life of the old horse passed in is called an argument, because Ta is a specific parameter value! print(MyFirstFunction.__doc__) # name is a formal parameter during function definition help(MyFirstFunction) # Help on function MyFirstFunction in module __main__: # MyFirstFunction(name) # name is a formal parameter during function definition

1.4 function parameters

Python functions have very flexible parameter forms, which can not only realize simple calls, but also pass in very complex parameters. The parameters from simple to complex are as follows:

  • Positional argument
  • Default parameter: default argument
  • variable argument
  • Keyword parameter keyword argument
  • name keyword argument
  • Parameter combination

1. Position parameters

def functionname(arg1): "Function document string" functionsuite return [expression]
  • arg1 - location parameters, which should be fixed when calling the function.

2. Default parameters

def functionname(arg1, arg2=v): "Function document string" functionsuite return [expression]
  • arg2 = v - default parameter = default value. When calling the function, the value of the default parameter is considered as the default value if it is not passed in.
  • The default parameter must be placed behind the location parameter, otherwise an error will be reported.
def printinfo(name, age=8): print('Name:,Age:'.format(name, age)) printinfo('pony') # Name: pony, Age:8 printinfo('pony', 10) # Name: pony, Age:10
  • Python allows the order of parameters when a function is called to be inconsistent with that when declared, because the Python interpreter can match parameter values with parameter names.
def printinfo(name, age): print('Name:,Age:'.format(name, age)) printinfo(age=8, name='pony') # Name: pony, Age:8

3. Variable parameters

As the name suggests, a variable parameter means that the number of parameters passed in is variable. It can be 0, 1, 2 to any number. It is a variable length parameter.

def functionname(arg1, arg2=v, *args): "Function document string" functionsuite return [expression]
  • *args - variable parameters, which can be from zero to any number, automatically assembled into a meta group.
  • Variable names with an asterisk (*) will store all unnamed variable parameters.
def printinfo(arg1, *args): print(arg1) for var in args: print(var) printinfo(10) # 10 printinfo(70, 60, 50) # 70 # 60 # 50

4. Keyword parameters

def functionname(arg1, arg2=v, args, **kw): "Function document string" functionsuite return [expression]
  • **kw - keyword parameters, which can be from zero to any number, are automatically assembled into a dictionary
def printinfo(arg1, *args, **kwargs): print(arg1) print(args) print(kwargs) printinfo(70, 60, 50) # 70 # (60, 50) # {} printinfo(70, 60, 50, a=1, b=2) # 70 # (60, 50) # {'a': 1, 'b': 2}

The similarities and differences between variable parameters and keyword parameters are summarized as follows:

  • Variable parameters allow zero to any parameters to be passed in, which are automatically assembled into a tuple when a function is called.
  • Keyword parameters allow zero to any parameters to be passed in, which are automatically assembled into a dictionary (dict) within the function.

5. Name keyword parameters

def functionname(arg1, arg2=v, args, *, nkw, *kw): "Function document string" functionsuite return [expression]
  • *, nkw  - Named keyword parameter. The keyword parameter that the user wants to enter is defined by adding a separator in front of nkw  *.
  • If you want to restrict the name of keyword parameters, you can use "name keyword parameters"
  • When using named keyword parameters, pay special attention to the absence of parameter names.

6. Parameter combination

To define a function in Python, you can use positional parameters, default parameters, variable parameters, named keyword parameters and keyword parameters. Four of the five parameters can be used together, but note that the order of parameter definitions must be:

  • Positional parameters, default parameters, variable parameters, and keyword parameters.
  • Positional parameters, default parameters, named keyword parameters, and keyword parameters.

Note the syntax for defining variable parameters and keywords:

  • *args   Is a variable parameter, args   Received is a   tuple
  • **kw   Is a keyword parameter, kw   Received is a   dict

Naming keyword parameters is to limit the parameter names that can be passed in by the caller, and provide default values. When defining named keyword parameters, don't forget to write separators  *, Otherwise, position parameters are defined.

Warning: Although up to 5 parameters can be combined, do not use too many combinations at the same time, otherwise the function is difficult to understand.

1.5 return value of function

def add(a, b): return a + b print(add(1, 2)) # 3 print(add([1, 2, 3], [4, 5, 6])) # [1, 2, 3, 4, 5, 6]
def back(): return [1, 'Pony's procedural life', 3.14] print(back()) # [1, 'pony's procedural life', 3.14]
def back(): return 1, 'Pony's procedural life', 3.14 print(back()) # (1, 'pony's procedural life', 3.14)
def printme(str): print(str) temp = printme('hello') # hello print(temp) # None print(type(temp)) # <class 'NoneType'>

1.6 variable scope

  • In Python, program variables are not accessible anywhere, and access permissions depend on where the variable is assigned.
  • 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 inside the declared function, while global variables can be accessed throughout the program.
def discounts(price, rate): final_price = price * rate return final_price old_price = float(input('Please enter the original price:')) # 98 rate = float(input('Please enter discount rate:')) # 0.9 new_price = discounts(old_price, rate) print('What is the price after discount:%.2f' % new_price) # 88.20
  • When the internal scope wants to modify the variables of the external scope, the global and nonlocal keywords are used. (Global is used to modify global variables and nonlocal is used to modify upper level variables)
num = 1 def fun1(): global num # global keyword declaration is required print(num) # 1 num = 123 print(num) # 123 fun1() print(num) # 123

Nested Function

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

closure

  • Is an important syntax structure of functional programming and a special embedded function.
  • If an internal function refers to an external non global scoped variable, the internal function is considered a closure.
  • You can access variables with an outer non global scope through closures. This scope is called   Closure scope.
def funX(x): def funY(y): return x * y return funY i = funX(8) print(type(i)) # <class 'function'> print(i(5)) # 40
#The return value of a closure is usually a function def make_counter(init): counter = [init] def inc(): counter[0] += 1 def dec(): counter[0] -= 1 def get(): return counter[0] def reset(): counter[0] = init return inc, dec, get, reset inc, dec, get, reset = make_counter(0) inc() inc() inc() print(get()) # 3 dec() print(get()) # 2 reset() print(get()) # 0
#The nonlocal keyword is required if you want to modify variables in the closure scope def outer(): num = 10 def inner(): nonlocal num # nonlocal keyword declaration num = 100 print(num) inner() print(num) outer() # 100 # 100

recursion

  • If a function calls itself internally, the function is a recursive function.
# n! Utilization cycle n = 5 for k in range(1, 5): n = n * k print(n) # 120 # Using recursion def factorial(n): if n == 1: return 1 return n * factorial(n - 1) print(factorial(5)) # 120
#Fibonacci sequence f (n) = f (n-1) + F (n-2), f (0) = 0, f (1) = 1 i = 0 j = 1 lst = list([i, j]) for k in range(2, 11): k = i + j lst.append(k) i = j j = k print(lst) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] # Using recursion def recur_fibo(n): if n <= 1: return n return recur_fibo(n - 1) + recur_fibo(n - 2) lst = list() for k in range(11): lst.append(recur_fibo(k)) print(lst) # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
  • Set the number of recursion layers. Python's default number of recursion layers is 100
import sys sys.setrecursionlimit(1000)
2. Lambda expression

2.1 definition of anonymous function

There are two types of functions in Python:

  • Class I: use   def   Keyword defined normal function
  • Class II: use   lambda   Keyword defined anonymous function

Python use   lambda   Keyword to create an anonymous function instead of def keyword. It has no function name, and its syntax structure is as follows:

lambda argument_list: expression
  • lambda  - Define keywords for anonymous functions.
  • argument_list  - Function parameters, which can be positional parameters, default parameters and keyword parameters, are the same as the parameter types in normal functions.
  • : - colon. Add a colon between the function parameter and the expression.
  • expression  - Just an expression, input function parameters and output some values.

be careful:

  • expression   There is no return statement in because lambda does not need it to return. The result of the expression itself is the return value.
  • Anonymous functions have their own namespace and cannot access parameters outside their own parameter list or in the global namespace.
def sqr(x): return x ** 2 print(sqr) # <function sqr at 0x000000BABD3A4400> y = [sqr(x) for x in range(10)] print(y) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] lbd_sqr = lambda x: x ** 2 print(lbd_sqr) # <function <lambda> at 0x000000BABB6AC1E0> y = [lbd_sqr(x) for x in range(10)] print(y) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] sumary = lambda arg1, arg2: arg1 + arg2 print(sumary(10, 20)) # 30 func = lambda *args: sum(args) print(func(1, 2, 3, 4, 5)) # 15

2.2 application of anonymous functions

Functional programming means that every piece of code is immutable and consists of pure functions. The pure function here means that the function itself is independent and does not affect each other. For the same input, there will always be the same output without any side effects.

#Non functional programming def f(x): for i in range(0, len(x)): x[i] += 10 return x x = [1, 2, 3] f(x) print(x) # [11, 12, 13]
#Functional programming def f(x): y = [] for item in x: y.append(item + 10) return y x = [1, 2, 3] f(x) print(x) # [1, 2, 3]

Anonymous functions are often used in high-order functions of functional programming, mainly in two forms:

  • The parameter is a function (filter, map)
  • The return value is the function (closure)

For example, in   Application in filter and map functions:

  • filter(function, iterable)   Filter the sequence, filter out the unqualified elements, and return an iterator object. If you want to convert it to a list, you can use   list()   To convert.
odd = lambda x: x % 2 == 1 templist = filter(odd, [1, 2, 3, 4, 5, 6, 7, 8, 9]) print(list(templist)) # [1, 3, 5, 7, 9]
  • map(function, *iterables)   Map the specified sequence according to the provided function.
m1 = map(lambda x: x ** 2, [1, 2, 3, 4, 5]) print(list(m1)) # [1, 4, 9, 16, 25] m2 = map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]) print(list(m2)) # [3, 7, 11, 15, 19]

In addition to Python built-in functions, we can also define high-order functions ourselves.

def apply_to_list(fun, some_list): return fun(some_list) lst = [1, 2, 3, 4, 5] print(apply_to_list(sum, lst)) # 15 print(apply_to_list(len, lst)) # 5 print(apply_to_list(lambda x: sum(x) / len(x), lst)) # 3.0
3. Class and object

3.1 object = attribute + method

An object is an instance of a class. In other words, classes mainly define the structure of objects, and then we use classes as templates to create objects. Class contains not only method definitions, but also data shared by all instances.

  • Encapsulation: Information Hiding Technology

We can use keywords   class   Define Python classes with keywords followed by the class name, semicolon, and class implementation.

class Turtle: # The class name convention in Python starts with an uppercase letter """A simple example of a class""" # attribute color = 'green' weight = 10 legs = 4 shell = True mouth = 'Big mouth' # method def climb(self): print('I'm trying to climb forward...') def run(self): print('I'm running fast...') def bite(self): print('Bite you, bite you!!') def eat(self): print('It's satisfying to have something to eat...') def sleep(self): print('Sleepy, asleep, good night, zzz') tt = Turtle() print(tt) # <__main__.Turtle object at 0x0000007C32D67F98> print(type(tt)) # <class '__main__.Turtle'> print(tt.__class__) # <class '__main__.Turtle'> print(tt.__class__.__name__) # Turtle tt.climb() # I'm trying to climb forward tt.run() # I'm running fast tt.bite() # Bite you, bite you!! # Python classes are also objects. They are instances of type print(type(Turtle)) # <class 'type'>
  • Inheritance: a mechanism for subclasses to automatically share data and methods between parent classes
class MyList(list): pass lst = MyList([1, 5, 2, 7, 8]) lst.append(9) lst.sort() print(lst) # [1, 2, 5, 7, 8, 9]
  • Polymorphism: different objects respond to different actions for the same method
class Animal: def run(self): raise AttributeError('Subclasses must implement this method') class People(Animal): def run(self): print('People are walking') class Pig(Animal): def run(self): print('pig is walking') class Dog(Animal): def run(self): print('dog is running') def func(animal): animal.run() func(Pig()) # pig is walking

3.2 what is self

self in Python is equivalent to this pointer in c + +.

class Test: def prt(self): print(self) print(self.__class__) t = Test() t.prt() # <__main__.Test object at 0x000000BC5A351208> # <class '__main__.Test'>

Class methods are only different from ordinary functions -- they must have an additional first parameter name (corresponding to the instance, that is, the object itself). By convention, its name is   self. When calling a method, we do not need to explicitly provide the and parameters   self   Corresponding parameters.

class Ball: def setName(self, name): self.name = name def kick(self): print("My name is%s,Damn it, who kicked me..." % self.name) a = Ball() a.setName("ball A") b = Ball() b.setName("ball B") c = Ball() c.setName("ball C") a.kick() # My name is ball A, damn it, who kicked me b.kick() # My name is ball B. damn it, who kicked me

3.3 Python's magic method

It is said that Python objects naturally have some magical methods. They are everything in object-oriented Python

They are special ways to add magic to your classes

If your object implements one of these methods, this method will be called by Python under special circumstances, and all this will happen automatically

Class has a name__ init__(self[, param1, param2...]), which will be called automatically when the class is instantiated.

class Ball: def __init__(self, name): self.name = name def kick(self): print("My name is%s,Damn it, who kicked me..." % self.name) a = Ball("ball A") b = Ball("ball B") c = Ball("ball C") a.kick() # My name is ball A, damn it, who kicked me b.kick() # My name is ball B. damn it, who kicked me

3.4 public and private

To define a private variable in Python, you only need to underline the variable name or function name with "_", then the function or variable will be private.

#Class class JustCounter: __secretCount = 0 # private variable publicCount = 0 # Public variable def count(self): self.__secretCount += 1 self.publicCount += 1 print(self.__secretCount) counter = JustCounter() counter.count() # 1 counter.count() # 2 print(counter.publicCount) # 2 # Python's private is pseudo private print(counter._JustCounter__secretCount) # 2 print(counter.__secretCount) # AttributeError: 'JustCounter' object has no attribute '__secretCount'
#Class class Site: def __init__(self, name, url): self.name = name # public self.__url = url # private def who(self): print('name : ', self.name) print('url : ', self.__url) def __foo(self): # Private method print('This is a private method') def foo(self): # Public method print('This is a public method') self.__foo() x = Site('Little garbage learning software', 'https://blog.csdn.net/qq_36798713') x.who() # name: Little garbage of learning software # url : https://blog.csdn.net/qq_36798713 x.foo() # This is a public method # This is a private method x.__foo() # AttributeError: 'Site' object has no attribute '__foo'

3.5 succession

Python also supports class inheritance. The definition of derived classes is as follows:

class DerivedClassName(BaseClassName): statement-1 . . . statement-N

BaseClassName must be defined in the same scope as the derived class. In addition to classes, you can also use expressions, which is very useful when the base class is defined in another module:

class DerivedClassName(modname.BaseClassName): statement-1 . . . statement-N

If a method or property with the same name as the parent class is defined in a subclass, the method or property corresponding to the parent class will be automatically overwritten.

# Class definition class people: # Define basic properties name = '' age = 0 # Define private properties, which cannot be accessed directly outside the class __weight = 0 # Define construction method def __init__(self, n, a, w): self.name = n self.age = a self.__weight = w def speak(self): print("%s say: I %d Years old." % (self.name, self.age)) # Single inheritance example class student(people): grade = '' def __init__(self, n, a, w, g): # Call the constructor of the parent class people.__init__(self, n, a, w) self.grade = g # Override method of parent class def speak(self): print("%s say: I %d Years old, I'm reading %d grade" % (self.name, self.age, self.grade)) s = student('Little garbage learning software', 10, 60, 3) s.speak() # The little garbage who studies software said: I'm 10 years old. I'm in grade 3

Note: if the above program removes: people__ init__ (self, N, a, w), then output: I'm 0 years old. I'm in grade 3 because the construction method of the subclass covers the construction method of the parent class.

import random class Fish: def __init__(self): self.x = random.randint(0, 10) self.y = random.randint(0, 10) def move(self): self.x -= 1 print("My position", self.x, self.y) class GoldFish(Fish): # Goldfish pass class Carp(Fish): # carp pass class Salmon(Fish): # salmon pass class Shark(Fish): # shark def __init__(self): self.hungry = True def eat(self): if self.hungry: print("The dream of eating goods is to eat every day!") self.hungry = False else: print("Too much to eat!") self.hungry = True g = GoldFish() g.move() # My position 9 4 s = Shark() s.eat() # The dream of eating goods is to eat every day! s.move() # AttributeError: 'Shark' object has no attribute 'x'

There are two ways to solve this problem:

  • Call the unbound parent class method fish__ init__ (self)
class Shark(Fish): # shark def __init__(self): Fish.__init__(self) self.hungry = True def eat(self): if self.hungry: print("The dream of eating goods is to eat every day!") self.hungry = False else: print("Too much to eat!") self.hungry = True
  • Use the super function super()__ init__ ()
class Shark(Fish): # shark def __init__(self): super().__init__() self.hungry = True def eat(self): if self.hungry: print("The dream of eating goods is to eat every day!") self.hungry = False else: print("Too much to eat!") self.hungry = True

Although Python supports the form of multiple inheritance, we generally do not use multiple inheritance because it is easy to cause confusion.

class DerivedClassName(Base1, Base2, Base3): statement-1 . . . statement-N

Note the order of parent classes in parentheses. If the parent class has the same method name and is not specified when the child class is used, Python searches from left to right, that is, if the method is not found in the child class, it searches from left to right whether the parent class contains a method.

# Class definition class People: # Define basic properties name = '' age = 0 # Define private properties, which cannot be accessed directly outside the class __weight = 0 # Define construction method def __init__(self, n, a, w): self.name = n self.age = a self.__weight = w def speak(self): print("%s say: I %d Years old." % (self.name, self.age)) # Single inheritance example class Student(People): grade = '' def __init__(self, n, a, w, g): # Call the constructor of the parent class People.__init__(self, n, a, w) self.grade = g # Override method of parent class def speak(self): print("%s say: I %d Years old, I'm reading %d grade" % (self.name, self.age, self.grade)) # Another class, preparation before multiple inheritance class Speaker: topic = '' name = '' def __init__(self, n, t): self.name = n self.topic = t def speak(self): print("My name is %s,I am a speaker. The theme of my speech is %s" % (self.name, self.topic)) # multiple inheritance class Sample01(Speaker, Student): a = '' def __init__(self, n, a, w, g, t): Student.__init__(self, n, a, w, g) Speaker.__init__(self, n, t) # The method name is the same. By default, the method of the parent class listed in parentheses is called test = Sample01("Tim", 25, 80, 4, "Python") test.speak() # My name is Tim. I'm a speaker. The theme of my speech is Python class Sample02(Student, Speaker): a = '' def __init__(self, n, a, w, g, t): Student.__init__(self, n, a, w, g) Speaker.__init__(self, n, t) # The method name is the same. By default, the method of the parent class listed in parentheses is called test = Sample02("Tim", 25, 80, 4, "Python") test.speak() # Tim said: I'm 25 years old. I'm in grade 4

3.6 combination

class Turtle: def __init__(self, x): self.num = x class Fish: def __init__(self, x): self.num = x class Pool: def __init__(self, x, y): self.turtle = Turtle(x) self.fish = Fish(y) def print_num(self): print("There are turtles in the pool%s One, little fish%s strip" % (self.turtle.num, self.fish.num)) p = Pool(2, 3) p.print_num() # There are two turtles and three small fish in the pool

3.7 class, class object and instance object

Class object: creating a class is actually an object, which also opens up a space in memory, called class object. There is only one class object.

Instance object: an object created by instantiating a class, which is called an instance object. There can be multiple instance objects.

class A(object): pass # Instantiated objects a, b and c all belong to instance objects. a = A() b = A() c = A()

Class attribute: variables defined outside methods in a class are called class attributes. The class attribute belongs to the class object, and multiple instance objects share the same class attribute. In other words, the class attribute can be shared by all objects instantiated through the class.

class A(): a = 0 #Class properties def __init__(self, xx): A.a = xx #Using class properties can be called through (class name. Class property).

Instance property: instance property is related to a specific instance object, and an instance object and another instance object do not share properties. In other words, instance property can only be used in their own objects, and other objects cannot be used directly, because the value of self belongs to the object who calls it.

# create a class object class Test(object): class_attr = 100 # Class properties def __init__(self): self.sl_attr = 100 # Instance properties def func(self): print('Class object.Value of class property:', Test.class_attr) # Call class properties print('self.Value of class property', self.class_attr) # It is equivalent to changing class properties into instance properties print('self.The value of the instance property', self.sl_attr) # Call instance properties a = Test() a.func() # Class object. Value of class attribute: 100 # The value of the self. Class attribute is 100 # self. The value of the instance property is 100 b = Test() b.func() # Class object. Value of class attribute: 100 # The value of the self. Class attribute is 100 # self. The value of the instance property is 100 a.class_attr = 200 a.sl_attr = 200 a.func() # Class object. Value of class attribute: 100 # The value of the self. Class attribute is 200 # self. Value of instance property 200 b.func() # Class object. Value of class attribute: 100 # The value of the self. Class attribute is 100 # self. The value of the instance property is 100 Test.class_attr = 300 a.func() # Class object. Value of class attribute: 300 # The value of the self. Class attribute is 200 # self. Value of instance property 200 b.func() # Class object. Value of class attribute: 300 # The value of the self. Class attribute is 300 # self. The value of the instance property is 100

Note: the attribute is the same as the method name, and the attribute overrides the method.

class A: def x(self): print('x_man') aa = A() aa.x() # x_man aa.x = 1 print(aa.x) # 1 aa.x() # TypeError: 'int' object is not callable

3.8 what is binding

Python strictly requires that methods need instances to be called. This restriction is actually Python's so-called binding concept.

The data properties of Python objects are usually stored in a file named__ dict__ In the dictionary, we can access it directly__ dict__, Or use Python's built - in function vars()__ dict__.

class CC: def setXY(self, x, y): self.x = x self.y = y def printXY(self): print(self.x, self.y) dd = CC() print(dd.__dict__) # {} print(vars(dd)) # {} print(CC.__dict__) # {'__module__': '__main__', 'setXY': <function CC.setXY at 0x000000C3473DA048>, 'printXY': <function CC.printXY at 0x000000C3473C4F28>, '__dict__': <attribute '__dict__' of 'CC' objects>, '__weakref__': <attribute '__weakref__' of 'CC' objects>, '__doc__': None} dd.setXY(4, 5) print(dd.__dict__) # {'x': 4, 'y': 5} print(vars(CC)) # {'__module__': '__main__', 'setXY': <function CC.setXY at 0x000000632CA9B048>, 'printXY': <function CC.printXY at 0x000000632CA83048>, '__dict__': <attribute '__dict__' of 'CC' objects>, '__weakref__': <attribute '__weakref__' of 'CC' objects>, '__doc__': None} print(CC.__dict__) # {'__module__': '__main__', 'setXY': <function CC.setXY at 0x000000632CA9B048>, 'printXY': <function CC.printXY at 0x000000632CA83048>, '__dict__': <attribute '__dict__' of 'CC' objects>, '__weakref__': <attribute '__weakref__' of 'CC' objects>, '__doc__': None}

3.9 some related built-in functions

  • issubclass(class, classinfo)   Method is used to determine whether the parameter class is a subclass of the type parameter classInfo.
  • A class is considered a subclass of itself.
  • classinfo can be a tuple of a class object. As long as class is a subclass of any candidate class, it returns True.
class A: pass class B(A): pass print(issubclass(B, A)) # True print(issubclass(B, B)) # True print(issubclass(A, B)) # False print(issubclass(B, object)) # True
  • isinstance(object, classinfo)   Method is used to determine whether an object is a known type, similar to type().
  • type() does not consider a subclass as a parent type and does not consider inheritance.
  • isinstance() will consider the subclass as a parent type and consider the inheritance relationship.
  • If the first parameter is not an object, False is always returned.
  • If the second parameter is not a class or a tuple composed of class objects, a TypeError exception will be thrown.
a = 2 print(isinstance(a, int)) # True print(isinstance(a, str)) # False print(isinstance(a, (str, int, list))) # True class A: pass class B(A): pass print(isinstance(A(), A)) # True print(type(A()) == A) # True print(isinstance(B(), A)) # True print(type(B()) == A) # False
  • hasattr(object, name) is used to judge whether an object contains corresponding attributes.
class Coordinate: x = 10 y = -5 z = 0 point1 = Coordinate() print(hasattr(point1, 'x')) # True print(hasattr(point1, 'y')) # True print(hasattr(point1, 'z')) # True print(hasattr(point1, 'no')) # False
  • getattr(object, name[, default]) is used to return an object attribute value.
class A(object): bar = 1 a = A() print(getattr(a, 'bar')) # 1 print(getattr(a, 'bar2', 3)) # 3 print(getattr(a, 'bar2')) # AttributeError: 'A' object has no attribute 'bar2'
class A(object): def set(self, a, b): x = a a = b b = x print(a, b) a = A() c = getattr(a, 'set') c(a='1', b='2') # 2 1
  • setattr(object, name, value) corresponding function   getattr() is used to set the attribute value, which does not necessarily exist.
class A(object): bar = 1 a = A() print(getattr(a, 'bar')) # 1 setattr(a, 'bar', 5) print(a.bar) # 5 setattr(a, "age", 28) print(a.age) # 28
  • delattr(object, name) is used to delete attributes.
class Coordinate: x = 10 y = -5 z = 0 point1 = Coordinate() print('x = ', point1.x) # x = 10 print('y = ', point1.y) # y = -5 print('z = ', point1.z) # z = 0 delattr(Coordinate, 'z') print('--delete z After attribute--') # --After deleting the z attribute-- print('x = ', point1.x) # x = 10 print('y = ', point1.y) # y = -5 # Trigger error print('z = ', point1.z) # AttributeError: 'Coordinate' object has no attribute 'z'
  • class property([fget[, fset[, fdel[, doc]]]]) is used to return property values in new classes.
    • fget  -- Function to get property value
    • fset  -- Function to set property value
    • fdel  -- Delete attribute value function
    • doc  -- Attribute description information
class C(object): def __init__(self): self.__x = None def getx(self): return self.__x def setx(self, value): self.__x = value def delx(self): del self.__x x = property(getx, setx, delx, "I'm the 'x' property.") cc = C() cc.x = 2 print(cc.x) # 2 del cc.x print(cc.x) # AttributeError: 'C' object has no attribute '_C__x'
4 magic methods

Magic methods are always surrounded by double underscores, such as__ init__.

Magic method is everything about object-oriented Python. If you don't know magic method, you haven't realized the power of object-oriented Python.

The "magic" of magic methods is that they can always be called automatically at the right time.

The first parameter of the magic method should be cls (class method) or self (instance method).

  • cls: represents the name of a class
  • self: represents the name of an instance object

4.1 basic magic methods

  • __ init__(self[, ...])   Constructor, the initialization method called when an instance is created
class Rectangle: def __init__(self, x, y): self.x = x self.y = y def getPeri(self): return (self.x + self.y) * 2 def getArea(self): return self.x * self.y rect = Rectangle(4, 5) print(rect.getPeri()) # 18 print(rect.getArea()) # 20
  • __ new__(cls[, ...])   The first method called when an object is instantiated is called__ init__ Call before initialization__ new__.
    • __ new__ There must be at least one parameter cls, representing the class to be instantiated. This parameter is automatically provided by the Python interpreter during instantiation, and the following parameters are directly passed to the__ init__.
    • __ new__ Instantiate the current class, return the instance, and pass it to__ init__ self. However, it was implemented__ new__, Not necessarily__ init__, Only__ new__ Returns the instance of the current class cls and the__ init__ To enter.
class A(object): def __init__(self, value): print("into A __init__") self.value = value def __new__(cls, *args, **kwargs): print("into A __new__") print(cls) return object.__new__(cls) class B(A): def __init__(self, value): print("into B __init__") self.value = value def __new__(cls, *args, **kwargs): print("into B __new__") print(cls) return super().__new__(cls, *args, **kwargs) b = B(10) # result: # into B __new__ # <class '__main__.B'> # into A __new__ # <class '__main__.B'> # into B __init__ class A(object): def __init__(self, value): print("into A __init__") self.value = value def __new__(cls, *args, **kwargs): print("into A __new__") print(cls) return object.__new__(cls) class B(A): def __init__(self, value): print("into B __init__") self.value = value def __new__(cls, *args, **kwargs): print("into B __new__") print(cls) return super().__new__(A, *args, **kwargs) # Changed cls to A b = B(10) # result: # into B __new__ # <class '__main__.B'> # into A __new__ # <class '__main__.A'>

14 October 2021, 03:49 | Views: 5587

Add new comment

For adding a comment, please log in
or create account

0 comments