SoFunction
Updated on 2025-03-01

python object-oriented reflection principle analysis

1. Static methods and class methods

Class method: There is a default parameter cls, and it can be called directly with the class name, which can be used with the class attribute ××× (that is, you can use the class attributes)

Static method: Let the methods in the class be called directly by the class, just like calling a function normally

The similarities between class methods and static methods: both can be called directly by the class without instantiation

The differences between class methods and static methods:

  • The class method must have a cls parameter to represent this class, and you can use the class attributes.
  • Static methods do not require parameters

Binding methods: divided into ordinary methods and class methods

  • Normal method: By default, a self object is passed in, and can only be called by the object-----------binding to the object
  • Class method: By default, a cls object is passed in and can be called by classes and objects (not recommended) ------binded to the class
  • Non-binding method: Static method: No default parameters are set, and can be called by classes and objects (not recommended) -------Non-binding
import time
class Date:
  def __init__(self,year,month,day):
    =year
    =month
    =day
  # @staticmethod
  # def now():
  #   t=()
  #   return Date(t.tm_year,t.tm_mon,t.tm_mday)
  @classmethod     #Change into class method  def now(cls):
    t=()
    return cls(t.tm_year,t.tm_mon,t.tm_mday) #Which class is used to call, that is, which class cls is used to instantiate itclass EuroDate(Date):
  def __str__(self):
    return 'year:%s month:%s day:%s' %(,,)
e=()
print(e)        #We want to trigger EuroDate.__str__, at this time e is generated by EuroDate, and the result is as we wish'''
 Output result:
 year:2017 month:3 day:3
 '''

2. Reflection

Reflection: You can access the object's properties in the form of a string, call the object's methods (but you cannot access the methods). Everything in python is an object, and reflection can be used.

There are four ways to reflect:

hasattr:hasattr (object, name) determines whether an object has a name attribute or a name method. Return True if there is, and return False if there is no.

getattr:Gets the object's properties or method, and prints it out if it exists. hasattr and getattr are used together

It should be noted that if the method returned is the object, the memory address of the object is returned. If you need to run this method, you can add a pair of () at the end.

setattr:Assign values ​​to the object's attributes. If the attribute does not exist, create first and then assign values.

delattr:Delete an attribute specified by the object

1. Application of reflection in the object

class Foo:
  def __init__(self):
     = 'egon'
     = 51
  def func(self):
    print('hello')
egg = Foo()
print(hasattr(egg,'name'))   #First determine whether the name exists in egg, the result is Trueprint(getattr(egg,'name'))   #If it is True, it will get it, and the result is eggprint(hasattr(egg,'func'))   #The result is Trueprint(getattr(egg,'func'))   #What I got is the address <bound method of <__main__.Foo object at 0x00000000001DDA2E8>>getattr(egg,'func')()    #Put brackets here to get it, because func is the method, and the result is hello
The general usage is as follows,First determine whetherhasattr,Then takegetattr
if hasattr(egg,'func'):
  getattr(egg,'func')()  #The result is helloelse:
  print('Not found')

2. Class application reflection

class Foo:
  f = 123
  @classmethod
  def class_method_dome(cls):
    print('class_method_dome')
  @staticmethod
  def static_method_dome():
    print('static_method_dome')    
print(hasattr(Foo,'class_method_dome'))     #The result is Truemethod = getattr(Foo,'class_method_dome')
method()                #The result is class_method_dome
print(hasattr(Foo,'static_method_dome'))     #The result is Truemethod1 = getattr(Foo,'static_method_dome')
method1()               #turn outstatic_method_dome

3. Module application reflection

# 1. Import other module references

import mymodule
print(hasattr(mymodule,'test'))
getattr(mymodule,'test')()
p = getattr(mymodule,'test')
p()               #Equivalent to the abovegetattr(mymodule,'test')()

# 2. Apply reflection in this module

def demo1():
  print('hello')
import sys
module_obj = [__name__]    #Equivalent to '__main__'print(module_obj)         #The result is <module '__main__' from 'C:/Users/Administrator/Desktop/'>print(hasattr(module_obj,'demo1'))    #The result is Truegetattr(module_obj,'demo1')()     #turn outhello

Example of importing your own module:

def register():
  print('regiester')
def Log in():
  print('login')
def Shopping():
  pass
print('Register, log in, shop')
ret = input('Please enter what you want to do:')
import sys
my_module = [__name__] #Use the sys module to import your own moduleif hasattr(my_module,ret):
  getattr(my_module,ret)()

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.