python learning records: classes, instance attributes, instance methods, class attributes, class methods, static methods, constructors, destructors, callable objects

1. Class Definition

  • The properties and methods of the data type are defined in the class;
  • Different objects of the same class share the methods of the class, but each has its own properties;

1.1 Defining the method

class class name:
	class body
  • Key Points:
    • Class names must conform to the rules for "identifiers"; as a general rule, the first letter is capitalized, and multiple words use the "CamelCase" principle;
    • Define properties and methods in the class body;
    • Attributes are used to describe data, and methods (that is, functions) are used to describe operations related to these data;

1.2 Constructor __init__()

  • The python object contains:
    • id
    • type
    • value
      • Attributes
      • method
  • Key Points:
    • The name is fixed and must be: init();
    • The first parameter must be: self;
    • The constructor is used to initialize the instance properties of the instance object;
    • The constructor is called through the "class name (parameter list)", and after the call, the created object is returned to the corresponding variable;
    • init() method: Initialize the created object;
    • new() method: used to create objects, generally there is no need to redefine this method;
    • The system will provide a default __init__ method. If the __init__ method with parameters is defined, the system will not create a default __init__ method;

1.3 Instance Properties

  • Properties subordinate to an instance object, also known as "instance variables";
  • Key Points:
    • definition:
      self.instance property name = initial value
      
    • access:
      self.instance property name
      
    • After creating an instance object, access it through the instance object:
      obj01 = class name()   #Create an object and call __init__() to initialize properties
      
      obj01.instance property name = value    #You can assign values ​​to existing properties, or you can add new properties
      

1.4 Instance Methods

  • subordinate to the method of the instance object;
  • definition:
    def method name(self [, parameter list])
    	function body
    
  • Key Points:
    • The first parameter must be self;
    • You do not need to pass parameters to self, and the interpreter will automatically pass parameters;
  • Difference between function and method:
    • essentially the same;
    • The method belongs to the instance object and needs to be called through the object, and the function does not need it;
    • You need to pass self when the method is defined, and the function does not need to;
  • Other operations:
    • dir(obj): Get all the properties and methods of the object;
    • obj.__dict__ : get the attribute dictionary of the object;
    • pass: empty statement;
    • isinstance( object, type): Determine whether the object is of the specified type;

2. Class objects

2.1 Class attributes

  • Class attributes are attributes subordinate to "class objects", also known as "class variables";
  • can be shared by all instance objects;
  • definition:
    class class name:
    	class variable name= initial value
    
class Student:
	company = "SXT" #class attribute
	count = 0 #class attribute
	
	def __init__(self,name,score):
		self.name = name #instance properties  
		self.score = score
		Student.count = Student.count+1
	
	def say_score(self): #instance method
		print("My company is:",Student.company)
		print(self.name,'The score is:',self.score)

2.2 Class Methods

  • class methods are subordinate to "class objects";

  • definition:
    Class methods are defined by the decorator @classmethod;

    @classmethod
    def class method name(cls [,parameter list]):
    	function body
    
    class Student:
    company = "SXT" #class attribute
    @classmethod
    def printCompany(cls):
    	print(cls.company)
    
    Student.printCompany()
    
  • Key Points:

    • @classmethod must be on the line above the method;
    • must have cls;
    • When calling, "class name. class method name (parameter list)", no need to pass a value to cls;
    • When the subclass inherits the parent class method, the incoming cls is the subclass object, not the parent class object;
    • Accessing instance properties and instance methods from within a class method method results in an error

2.3 Static methods

  • Methods that have nothing to do with "class objects" are called "static methods";

  • A "static method" is defined in a module in the same way as a normal function, but it is in the "class namespace" and needs to be called through the class when it is called;

  • definition:
    Defined by the decorator @staticmethod

    @staticmethod
    def static method name([parameter list]):
    	function body
    
    class Student:  
    	company = "SXT" # class attribute
    	@staticmethod  
    	def add(a, b): # static method  
    		print("{0}+{1}={2}".format(a,b,(a+b)))  
    	return a+b  
    Student.add(20,30)
    
  • Key Points:

    • @staticmethod must be on the line above the method;
    • When called, "class name. static method name (parameter list)";
    • Accessing instance properties and instance methods in static methods will cause errors;

2.4 __del__ method (destructor) and garbage collection mechanism

  • The __del__ method is used to implement the operations required when the object is destroyed;
  • Python can implement automatic garbage collection: when the object is not referenced (reference count is 0), the __del__ method is called by the garbage collector;
  • The system will automatically provide the __del__ method, which generally does not require a custom destructor method;
class Person:  
	def __del__(self):  
		print("Destroy the object:{0}".format(self))  
	
p1 = Person()  
p2 = Person()  
del p2  
print("program ends")

# Destroy object: <... >
# program ends
# Destroy object: <... >  

2.5 __call__ methods and callable objects

  • An object that defines the __call__ method can be called like a function;
class SalaryAccount:  
	def __call__(self, salary):
	yearSalary = salary*12
	daySalary = salary//22.5
	hourSalary = daySalary//8  
	return dict(yearSalary=yearSalary,
				monthSalary=salary,  
				daySalary=daySalary, 
				hourSalary=hourSalary)
				
s = SalaryAccount()  
print(s(30000)) 
# {'yearSalary': 360000, 'monthSalary': 30000, 'daySalary': 1333, 'hourSalary': 166}

Tags: Python

Posted by laura_richer on Sat, 23 Jul 2022 04:25:32 +0930