author :Java Academic lying Warehouse :Github、Gitee ️ Blog :CSDN、 Nuggets 、InfoQ、 cloud + Community important clause : Originality is not easy. , No reprint or plagiarize without authorization , If you need to reprint, you can contact Xiaobian for authorization . Copyright notice : Some words or pictures in the article come from the Internet and Baidu Encyclopedia , If there is infringement, please contact Xiaobian as soon as possible .
️ Daily poisonous chicken soup : There is injustice in this society , Don't complain , Because it doesn't work ! People always make progress in introspection !
Hello everyone ! I'm an old friend of yours Java Academic lying .
Add extra properties to the instance object of the class
# Add properties and methods dynamically
class Student(object):
def __init__(self, name, age):
self.name = name
self.age = age
pass
def __str__(self):
return ' full name :{}, Age :{}'.format(self.name, self.age)
pass
# Create a class instance object
student = Student(' Xiao Ming ', 30)
# Use the original properties of the class instance object
print(student.name)
# Dynamically add instance object properties . This is not the case with the class room attribute
# At this point, you just add extra to this object room attribute , Other instance objects will not have this room attribute
student.room = 'python Class two '
print(student.room)
# python Class two
student2 = Student(' Xiao Wang ', 40)
# student2 No, room attribute ,student It just adds extra room attribute
# print(student2.room) Report errors
Copy code
Add extra attributes to the class
# Add properties and methods dynamically
class Student(object):
def __init__(self, name, age):
self.name = name
self.age = age
pass
def __str__(self):
return ' full name :{}, Age :{}'.format(self.name, self.age)
pass
# Add attributes to the class . Point by class
Student.height = '175'
# Instance objects can access class properties .
# Instance objects can access class properties and instance properties
# Class can only access class properties , Instance properties are not accessible
student = Student(' Zhang San ', 30)
print(student.height)
# 175
Copy code
Dynamically add instance methods : Need to use types
# Add properties and methods dynamically
# Import the library for adding methods
import types
# Define dynamically added instance object methods
# The method of the defined instance object must exist self This parameter , Otherwise, an error will be reported when binding
# Even if this is not used in the method body self Parameters , Nor can it be omitted here
def show(self):
print('{} His height is :{}kg, The class is :{}'.format(self.name, self.height, Student.room))
print(1)
pass
class Student(object):
def __init__(self, name, age):
self.name = name
self.age = age
pass
def __str__(self):
return ' full name :{}, Age :{}'.format(self.name, self.age)
pass
student = Student(' Xiao Ming ', 20)
# Dynamically add instance object properties
student.height = '175'
# Dynamically add class properties
Student.room = 'python Class one '
# Dynamically add methods to the instance object .
# First we need to pass types.MethodType Binding method , The first parameter is the bound method name , The second is the instance object name
student.showInfo = types.MethodType(show, student)
# Call the instance method of dynamic binding
student.showInfo()
# Xiao Ming's height is :175kg, The class is :python Class one
# 1
student1 = Student(' Xiao Wang ', 30)
# At this point, add additional methods to the instance object , Just for student Added ,student1 You need to bind again
# student1.showInfo() Report errors
Copy code
Add class methods and static methods dynamically : Class name . Method name = xxx Formal binding class method
# Add properties and methods dynamically
# Import the library for adding methods
import types
# Define a class method
# This class method must exist cls This parameter , Whether the method body is used or not , Must be given this parameter
# Otherwise, an error will be reported when binding the method
@classmethod
def eat(cls):
print(' having dinner ')
pass
# Define a static method
# Static methods , This cls Parameters are optional
@staticmethod
def drink():
print(' Drink lots of water ')
pass
class Student(object):
def __init__(self, name, age):
self.name = name
self.age = age
pass
def __str__(self):
return ' full name :{}, Age :{}'.format(self.name, self.age)
pass
student = Student(' Xiao Ming ', 30)
# to Student Class binding class methods eat()
Student.eat = eat
# Call the extra class method
# The parameters here cannot be passed , If you give it, you will report an error
Student.eat()
# having dinner
# to Student Class binding additional static methods
Student.drink = drink
Student.drink()
# Drink lots of water
# Instance objects can access additional class methods and class static methods
student.eat()
student.drink()
Copy code
Usage mode
# adopt __slots__ Control the additional instance attributes and class attributes added
class Student(object):
def __init__(self, name, age):
self.name = name
self.age = age
pass
def __str__(self):
return ' full name :{}, Age :{}'.format(self.name, self.age)
# If you don't put name as well as age Attribute is added to this __slots__, So at this time name and age Is a read-only property , You cannot assign a new value
# When you create an object, you cannot give name and age assignment , So here we have to write these two parameters
__slots__ = ('sex', 'room', 'name', 'age')
pass
student = Student(' Xiao Ming ', 20)
print(student.name)
print(student.age)
# Add additional instance properties and __slots__ Existing in
student.sex = ' male '
print(student.sex)
# male
# Add additional instance properties , yes __slots__ There is no such thing as
# student.height = '186' Report errors
# Add extra attributes to the class and be __slots__ Existing in
Student.sex = ' male '
print(Student.sex)
# male
# Add additional instance properties , yes __slots__ There is no such thing as
# student.height = '186' Report errors
# If it doesn't exist __slots__ , Then all instance properties will be stored in a dictionary . Dictionaries are very memory intensive
# When it exists __slots__ When , All instance properties will not be stored in this dictionary , Instead, store the attributes in __slots__ variable
print(student.__dict__)
# {'name': ' Xiao Ming ', 'age': 20, 'sex': ' male '}
Copy code
slots Inheritance of variables between parent and child classes
Subclasses must declare slots Variables inherit from the parent class , Otherwise, it will not inherit
# adopt __slots__ Control the additional instance attributes and class attributes added
class People(object):
def __init__(self, name, age):
self.name = name
self.age = age
pass
def __str__(self):
return ' full name :{}, Age :{}'.format(self.name, self.age)
# If you don't put name as well as age Attribute is added to this __slots__, So at this time name and age Is a read-only property , You cannot assign a new value
# When you create an object, you cannot give name and age assignment , So here we have to write these two parameters
__slots__ = ('sex', 'room', 'name', 'age')
pass
class Student(People):
pass
student = Student(' petty thief ', 18)
# When subclasses do not declare slots Variables do not inherit from the parent class slots Variable
# At this point, you can dynamically add attribute values to subclasses at will
student.height = '165'
print(student.height)
# 165
class Teacher(People):
# Subclass declaration slots Variable , In this case, the parent class will be inherited and additional properties can be added
# Subclasses should try not to override the existing properties of the parent class . Repeated declarations will take up memory space
__slots__ = 'weight'
pass
teacher = Teacher(' Teacher wang ', 40)
# In inherited parent class slots Variable Properties in
print(' Teacher's name :{}, The age of the teacher :{}'.format(teacher.name, teacher.age))
# Teacher's name : Teacher wang , The age of the teacher :40
# At this point, the subclass inherits the parent class's slots Variable , You can't add attributes at will
# teacher.height = '175' Report errors , because slots Does not exist in the height attribute
# You can add slots Attribute values present in
teacher.weight = '50'
print(teacher.weight)
# 50