python day 7 (nested functions, object-oriented programming)

Nested functions (intrinsic functions)

Nested function
Usage scenarios:
1. Subpackage, data hiding
2. Implement DRY principle and avoid duplicate code inside function
3, closure

 def outer():
 	print('outer running')
 		def inner01
 		print('inner running)
 	inner01() #Can only be used internally
 outer()
#Print English and Chinese names by defining two functions
def printChineseName(name,familyName):
	print('{0},{1}'.format(familyName,name))
def printEnglishName(name,familyName):
	print('{0},{1}.format(name,familyNme)')

#Using nested function to implement the above code
def printName(isChinese,name,familyName):
	def inner_print(a,b): 
		print('{0},{1}'.format(a,b))
	if isChinese:
		inner_print(familyName,name)
	else:
		inner_print(name,familyNme)

nonlocal keyword

nonlocal is used to declare external local variables
Global is used to declare global variables

#Test the usage of local and global keywords
a=100 3global variable
defer outer():
	b=200
	def inner():
		c=300
		print('innerc:',c)
		nonlocal b #Use peripheral local variable b
		print('formerouterb:',b) #Print peripheral local variable b before changing
		b=400 #Assign the peripheral variable b to 400
	inner()
	print('outerb:',b) #The value of b changes to 400

print('globala:',a)
outer()

LEGB rules

When python looks up names, it queries according to LEGB rules: local – enclosed – global – built in
local refers to the inner method of a function or class
enclosed refers to a nested function (a function wraps another function, a closure)
Global refers to the global variables in the module
built in refers to the special name reserved by python for itself

# Test LEGB
str='global'
def outer():
	str='outer'
	def inner():
		str='inner'
		print(str)
	inner()
outer()

Return result:
inner (because it returns the latest str)

print(str) #This STR returns the str of build in
print(type(str)) #Returns the type of str

Return result:
<class: str>
<class: type>

Chapter six: Object Oriented Programming

object oriented programming (oop): the main idea is for large-scale software design
Features: strong expansibility, good readability, making programming as simple as building blocks
He puts the relevant methods of data and operation data into the object, and organizes the code and data in a way that is close to people's thinking, so as to improve the programming efficiency
python is a real object-oriented programming language and fully supports the basic functions of object-oriented. For example, inheritance, polymorphism, encapsulation, etc., but python also supports many programming paradigms such as process oriented and functional programming.
Everything in python is an object.

1, The difference between object-oriented and process oriented

Process oriented: executor thinking (find verbs from problems), suitable for writing small programs, and writing out the steps to complete a thing.
Object oriented: designer's thinking (looking for nouns from problems), suitable for writing large-scale programs, dividing a thing into many modules, and completing its steps one by one.

2, Evolution of objects

Simple data → array → structure → object
1. Simple data
Like 10, 20, 30 and so on, in the beginning of computer programming, they all wanted numbers like this
2. array
Put data of the same type together. (birds of a feather flock together)
3. structure
Put disallowing type related data together
4. object
Put different types, methods (functions) together

3, Definition of class

Code is organized by classes, and related objects are created at runtime
Class: objects of objects created
Define the properties (data), methods (behavior) of data types through classes, that is, the classes package comfort and state together
Syntax format:
class name:
Class body
The main points are as follows: the class name should conform to the rules of identifier: generally, the first letter should be capitalized, and the hump principle should be used for multiple words
We can define properties and methods in the class body
Property is used to describe data, and method base function is used to describe related operations of these data

class Student: #Class name is generally capitalized, and hump principle is used for multiple words
	#Properties in python need to be defined in a special method (constructor)
	def_init_(self,name,score): #Self must be in the first parameter, and the address of the newly created object at runtime is passed to self
		self.name=name
		self.score=score
	def say_score(self): #self must be in the first parameter
		print('{0}The scores for are:{1}'.format(self.name,self.score))
si=Student('vivi',100) #Two parameters passed
si.say_score()

4, Constructor? init

Class is abstract (template of object). We need to create instance object of class through this template, then we can use the function of class definition
An object of python includes the following parts:
1.id identification code
2.type object type
3.value of value object
① properties
② method
To create an object, you need to define the dog in the function ﹤ init (
The main points of init() are as follows:
1. Fixed name
2. The first parameter must be self
3. Constructors are usually used to initialize instance properties of instance objects, such as name and score
4. Call the constructor through the class name (parameter list). After calling, return the created object to the corresponding variable, such as: si=Student ('vivi ', 100)
5.init() method: initialize the created object. Initialization refers to assigning an instance property
6.new() method: used to create objects, but it is generally unnecessary to define this method

class Student: #Class name is generally capitalized, and hump principle is used for multiple words
	#Properties in python need to be defined in a special method (constructor)
	def_init_(self,name,score): #Equivalent to formatting, self must be in the first parameter, and the address of the newly created object at runtime is passed to self
		self.name=name
		self.score=score
	def say_score(self): #self must be in the first parameter
		print('{0}The scores for are:{1}'.format(self.name,self.score))
si=Student('vivi',100) #Two parameters passed
si.say_score()

The following figure shows the procedure of calling a class:

5, Instance properties

Instance properties are properties subordinate to instance objects, also known as instance variables. They have the following points:
1. The instance attribute is generally defined in the ﹤ init ﹐ method by the following code:
self instance property name = initial value
2. In other instance methods of this class, it is also accessed through self:
self instance property name
3. After creating an instance object, access it through the instance object:
Obj001 = class name () ා create the object, call ᦇ (init) to initialize the property
Obj001. Instance property name = value ××. You can assign values to existing properties or add new properties

6, Instance method

An instance method is a method subordinate to an instance object. Its definition format is as follows:
def method name (self, [, parameter list]):
Function body
The call format of the method is as follows:
Object. Method name ([argument list])

class Student: #Class name is generally capitalized, and hump principle is used for multiple words
	#Properties in python need to be defined in a special method (constructor)
	def_init_(self,name,score): #Self must be in the first parameter, and the address of the newly created object at runtime is passed to self
		self.name=name
		self.score=score
	def say_score(self): #self must be in the first parameter
		print('{0}The scores for are:{1}'.format(self.name,self.score))
s1=Student('vivi',100) #Two parameters passed
s1.say_score()
s1.age=18
s1.salary=3000

s2=Student('lucy',90)

class Student: #Class name is generally capitalized, and hump principle is used for multiple words
	#Properties in python need to be defined in a special method (constructor)
	def_init_(self,name,score): #Equivalent to formatting, self must be in the first parameter, and the address of the newly created object at runtime is passed to self
		self.name=name
		self.score=score
	def say_score(self): #self must be in the first parameter
		print('{0}The scores for are:{1}'.format(self.name,self.score))
si=Student('vivi',100) #Two parameters passed
si.say_score()
Student.say_score(s1) #The result is the same as above


The difference between function and method
All statements are used to complete a function. They are essentially the same
When method is called, it is called by object. Method is subordinate to specific instance object. Ordinary function does not have this feature
The function does not need to pass self when the method is defined.

7, Class object

When the interpreter executes a class statement, it creates a class object.

1. categories of attributes

Class properties are properties belonging to class objects, also known as class variables. Because class properties are subordinate to class objects, they can be shared by all instance objects.
Grammatical structure:
class name:
Class variable name = initial value
In a class or outside a class, you can use: 'class name. Class variable name 'to read and write.

class Student: 
  company='IBM'  #Class attribute
  count=0   #Class attribute
  def_init_(self,name,score): #Equivalent to formatting, self must be in the first parameter, and the address of the newly created object at runtime is passed to self
		self.name=name #Instance attribute
		self.score=score #Instance attribute
		Student.count=Student.count+1 
	def say_score(self):  #Example method
		print('My company is:',student.company)
		print('{0}The scores for are:{1}'.format(self.name,self.score))
s1=Student('vivi',100) #s1 here is an instance object, which is a new object created through the student class mold
s1.say_score() #Call the instance method in the instance object
print('Create altogether{0}individual Student Participants:'.format(Student.count))

The 2. method

Methods subordinate to class objects are defined by the decorator @ classmethod.
Syntax format:
@classmethod
def class method name (cls [, parameter list])
Function body
The main points are as follows:
1.@classmethod must be on the line above the method
2. The first cls must have something similar to self, which refers to the class object itself
3. Calling class method format: class name. Class method name (parameter list). In the parameter list, cls does not need or cannot be passed a value
4. Accessing instance properties and instance methods in class methods will cause errors
5. When a subclass inherits a parent method, the passed cls is a subclass object, not a parent object

class Student: 
  company='IBM'  #Class attribute
  count=0   #Class attribute
  @classmethod
  def printCompany(cls):
  print(cls.company)
Student.printCompany()

3. Static method

python allows you to define domain class object independent methods, which are called static methods
There is no difference between a static method and a normal function defined in a module, except that the static method is placed in the class namespace and needs to be called through a class
Syntax format:
@staticmethod
def static method name ([parameter list]):
Function body
The main points are as follows:
1.@staticmethod must be on the line above the method
2. Call static method format: 'class name. Static method name (parameter list)'
3. Accessing instance properties and methods in static methods will lead to errors

8, Methods (destructors) and garbage collection mechanism

The del uuu method is called the "destruct method", which is used to implement the operations needed when an object is destroyed, such as releasing the resources occupied by the object
python implements automatic garbage collection. When an object is not referenced (the reference count is 0), a garbage collector calls the \
We can also delete objects with del statements to ensure that the Del method is used
The system will automatically provide the "del" method, which generally does not need to be customized

class person:
	def __del__(self):
		print('Destroy objects{0}'.format(self))

p1=person()
p2=person()
del p2
print('Program end')

9, call methods and callable objects

An object that defines a call method is called a callable object and can be called like a function

class SalaryAccount:
	def __call__(self,salary):
	print('Wage calculation')
	return dict(monthsalary=salary)
s=SalaryAccount()
s(1000)

Published 7 original articles, won praise 0, visited 172
Private letter follow

Keywords: Python Programming Attribute

Added by jollyjumper on Sun, 01 Mar 2020 12:20:39 +0200