Dynamic addition of attributes and methods for python classes and instances, and dynamic addition of python instances
From types import MethodType
# Python is a dynamic language, so it can dynamically add attributes and methods to classes and instances.
# However, note: The method for dynamically adding an instance is only valid for this instance and invalid for other instances.
# However, the method added to the class is valid for the instances generated by the class.
Class Student (object ):
Pass
S = Student ()
S. name = "zrs" # Add dynamic attributes to the class
S. age = 22
Print (s. name)
Print (s. age)
Def set_age (self, age ):
Self. age = age
Return self. age
# The first parameter is the method to be added, and the second parameter is the Instance name.
S. set_age = MethodType (set_age, s) # use this function to add classes or instances.
Print (s. set_age (25 ))
Def set_name (self, name ):
Self. name = name
# Dynamically add methods to a class
Student. set_name = set_name
S1 = Student ()
S1.name = "zhognrongshun"
S1.age = 22
S1.set _name ("666 ")
Print (s1.name)
# It is a good thing that dynamic languages can dynamically add attributes and methods.
# What if I have to restrict the attributes of an instance?
Class Student2 (object ):
_ Slots _ = ("name", "age") # Only attributes can be added here
S11 = Student2 ()
S11.name = "zlzl"
S11.age = 22
# S11.score = 99 # error: 'student2' object has no attribute 'score'
Print (s11.name, s11.age)
# This is the second way to dynamically Add a class
# Create a method
Def set_age (self, arg ):
Self. age = arg
# Create a class
Class Student3 (object ):
Pass
# Directly use a class to create a method, but at this time it is still linked to create a method in the memory outside the class
Student3.set _ age = MethodType (set_age, Student3)
# At this time, when creating an instance, the external method set_age will also copy these instances and Student3 class will point to the same set_age Method
S21 = Student1 ()
S21.set _ age (60)
Print (s21.age) # view results