Basic knowledge of Python 2022-11-16 ★ Summary 88-96 classes

Class definition_The relationship between classes and objects

class definition

Subject: a cookie
Class: The mold that made this biscuit
A class defines the properties (data) and methods (behavior) of a data type
classes are also objects
Classes package behavior and state together

operate:

# create a class  
class Student: # Class names are generally capitalized with the first letter, and multiple words use the camel case principle  
    def __init__(self,name,score): # self: the current object itself, must be in the first parameter  
        self.name = name  
        self.score = score  
    def say_score(self): # self must be in the first parameter  
        print("{0}The score is{1}".format(self.name,self.score))  
s1 = Student("gaoqi", 18)  
s1.say_score()

My summary:

class class name(capitalized initial or camelCase):
	def __init__(self, parameter 1, parameter 2...):
		...

Constructor __init__()

part of the object

  • id
  • type
  • value
    • attribute attribute, parameter in init
    • method method

init points

The first parameter must be self, which refers to the constructed object, self can be changed to other aa, s
__init__(): Initialize the object, which is to assign values ​​​​to the instance attributes
__new__(): Create an object, but usually you don't need to define this method

instance attribute

Instance attributes: attributes belonging to instance objects, also known as instance variables

  • Use points:
    • Generally defined by the following code in the init method:
      • self. instance attribute name = initial value
    • Among other instance methods in this class, access:
      • self.InstanceName
    • After creating the instance object, access it through the instance object:
      • ·object01 = class name () # create an object, call init to initialize properties
      • object01.Instance attribute name = value # You can assign values ​​to existing attributes and add new attributes

Step by step to construct an instance:

  1. class class name:, a class object is constructed, and a "mold" object appears in the memory
    1. new method, create a class object
    2. def __init__(self, formal parameter 1, formal parameter 2...):init initialization method, assigning attributes and methods (methods are also attributes) to class objects
  2. s1=Student( actual parameter 1, actual parameter 2...)
  3. s1.salary = 3000, the newly added attributes of the object are subordinate to the object and do not affect the "mold", and other objects newly constructed with the mold will not have these attributes

Instance method_memory analysis method call process_dir()isinstance

instance method

An instance method is a method that belongs to an instance object
Definition format:

def method name(self[,parameter list]):
	method statement

Distinguish between instance methods and functions:
In essence, they are all statement blocks used to complete a function
the format is very similar
Method call, call s1.say_score() through the object, subordinate to a specific instance object
Method definition requires self, function does not

Main points:
When defining an instance method, the first parameter must be self, which refers to the current instance object
When calling an instance method, it is not necessary or possible to pass parameters to self. The interpreter automatically passes parameters, and self is the current object.

The essence of the method call of the instance object

# a Object a created by the Student class
# say_score(), method of the Student class

a.say_score() # typed code
Student.say_score(a) # interpreter translation

# The above two lines have the same meaning, the idea of ​​​​the interpreter: find the Student class, find the method, and put the class

![[Pasted image 20221116110445.png]]

other operations

dir(obj): Get all the properties and methods of the object
obj.__dict__, the attribute dictionary of the object
pass, empty statement

class Man:
	pass

isinstance (object, type), to determine whether the object is a specified type

class object

Instance objects: Cookies created through class objects
Class object: the mold itself

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

operate:

class Student:
	pass # empty statement
print(type(Student))
print(id(Student))

Stu2 = Student # The address of the class object Student is given to Stu2, instead of creating an instance object, the parentheses are the call
s1 = Stu2() # Create an instance object s1 through Student
print(s1)

type itself is a class, mold class
type(Student):
Use the mold of type to create a Student class object, and create a student according to the Student mold

Class attribute_Memory analysis creates the bottom layer of classes and objects

class attribute

Class attributes are attributes subordinate to "class objects", also known as "class objects", which are different from instance attributes, which are subordinate to instance objects
Can be shared by all instance objects
Defined by:

class className:
	class_attr = default_value

operate:

class Student:  
    company = "SXT" # class attribute  
    count = 0 # class attribute  
  
    def __init__(self, name, score):  
        self.name = name  
        self.score = score  
        Student.count = Student.count + 1  
    def say_score(self):  
        print("My company is:",Student.company)  
        print(self.name,'The score is:',self.score)  
  
s1 = Student('gaoqi',80)  
s1.say_score()  
print('Created in total{0}indivual Student object'.format(Student.count))

My summary: the method of the instance is actually the method of retrieving the class along the "umbilical cord", and does not create a new function
My summary: ❓Why can Student.count play a counting role? Because it is a class method? When will it be emptied?

Class method_static method_memory analysis diagram

class method

methods belonging to class objects,
Class methods are defined by the decorator @classmethod
Class methods are used to manipulate class objects
Definition format:

@classmethod
def class method name(cls [,parameter list]): # Must write cls, specifically class object
	function body

Main points:

  1. @classmethod must be on the line above the method
  2. The first cls must have, referring to the "class object" itself
  3. The format of calling a class method: class name. class method name (parameter list), in the parameter list, it is not necessary and cannot pass a value to cls

static method

Methods that have nothing to do with "class objects" are called "static methods"
Go with the ordinary functions defined in the module, but they are placed in the namespace of the class and need to be called through the class

Format:

@staticmethod
def static method name(parameter list):
	function body

Note: Neither static method nor class method can access instance object or instance method print(self.company) but print(cls.company).
My summary: static methods and class methods can be called through instance objects (but not accessible), because the interpreter will translate s1.say_score() into Student.say_score(s1), that is, it will return to the class object to find method

__del__() destructor and garbage collection mechanism

The __del__() method is called the destructor method
Used for: implementing the operations required when the object is destroyed, such as: releasing the resources occupied by the object,
Examples: open file resources, network connections, etc.

Python implements automatic garbage collection. When the object is not referenced (the number of references is 0), the __del__() method is called by the garbage collection period
The object can be deleted through the del statement, and the __del__() method is guaranteed to be called
The system will automatically provide this method, and generally there is no need to customize the destructor method

# Destructor  
class Person:  
    def __del__(self):  
        print('destroy object{0}'.format(self))  
p1 = Person()  
p2 = Person()  
  
del p2  
  
print('end of program')

result:

destroy object<__main__.Person object at 0x00000206ABB76710> # del p2 destroys p2
 end of program
 destroy object<__main__.Person object at 0x00000206ABB50ED0> # destroyed p1

❓Why does del p2 also print "destroyed object" when p2 is destroyed? It is because we have rewritten the del method, so that the del method has the function of printing "destroyed object"
❓Why is p1 destroyed after the program ends? Is it because p1 is not referenced after the program ends?

__call__() method and callable objects

The object that defines the call method is called a callable object, that is, the object can be called like a function
functions are objects

a = 30
b = 50
c = a+b
d = a.__add__(b)

aa()
obj()  → __call__()

My summary: __call__() is the role of () parentheses

# Test callable method __call__()  
class SalaryAccount:  
    def __call__(self, salary):  
        print("Payroll...")  
        yearSalary = salary*12  
        daySalary = salary//22.5 # The country stipulates the average number of working days per month  
        hourSalary = daySalary//8  
        return dict(yearSalary=yearSalary, monthsalary=salary, daySalary=daySalary, hourSalary=hourSalary)  
  
s = SalaryAccount()  # construct instance object
# s = SalaryAccount(3000) 
# The above line will report an error like this

print(s(3000)) # Call the instance object with call

My summary: Callable objects are different from other objects by calling s1.say_score(), s(3000) does not refer to the method through the instance object
☑️❓s=SalaryAccount(3000) does not work, is it because there is no init method to construct instance objects? Yes, just change it like this

# Test callable method __call__()  
class SalaryAccount:  
    def __init__(self, salary):  
        self.salary = salary  
    def __call__(self,b):  
        print("Payroll...")  
        yearSalary = self.salary*12  
        daySalary = self.salary//22.5 # The country stipulates the average number of working days per month  
        hourSalary = daySalary//8  
        return dict(yearSalary=yearSalary, monthsalary=self.salary, daySalary=daySalary, hourSalary=hourSalary,b=b)  
  
s = SalaryAccount(3000)  
print(s(2000))

result:

Payroll...
{'yearSalary': 36000, 'monthsalary': 3000, 'daySalary': 133.0, 'hourSalary': 16.0, 'b': 2000}

❓What is the use of callable objects?
My summary: The parameters of the callable object can be passed in from the instance object, directly calling the defined call method

❓Can an instance object have multiple callable methods?

Tags: Python programming language

Posted by lnenad on Fri, 18 Nov 2022 19:02:16 +1030