向动态创建的调用“super”的类添加方法

2024-04-25 18:02:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要创建一个动态生成的类,其中包含一个调用其父方法的方法。你知道吗

动态创建类的常用方法如下:

# I have a class ClassA...
class ClassA(object):
  def print_something(self):
    print('I am a method defined in ClassA')

# ... and I want to create a dynamically created class that inherits from ClassA
def class_s_factory(print_str):
  def print_something(self):
    print('I am a method defined in ClassS')
    print(print_str)
  cls = type('ClassS', (ClassA, ), {'print_something': print_something})
  return cls

# I can finally create an instance of ClassS and use the 'print_something' method

# Get a string from the database (for example)
print_str_database = 'I am a string from the database'

test_class = class_s_factory(print_str_database)
test_instance = test_class()
test_instance.print_something()

# This will print
# I am a method defined in ClassS
# I am a string from the database

如果我想在print_something中调用父方法呢? 我怎样才能改变它?例如:

def print_something(self):
  # CALL PARENT'S METHOD HERE! HOW?
  print('I am a method defined in ClassS')
  print(print_str)

我想要以下输出

# I am a method defined in ClassA
# I am a method defined in ClassS
# I am a string from the database

我尝试了一些我提出的答案。这是可行的,但是有没有更好的方法来处理这种情况呢?你知道吗


Tags: the方法infromdefamdatabasemethod
1条回答
网友
1楼 · 发布于 2024-04-25 18:02:33

以下是我最后尝试的,而且很有效:

class ClassA(object):
  def print_something(self):
    print('I am a method defined in ClassA')

# Create a factory for classes.
# Each class has a method that depends on the string given
# This method needs to call its parent's method
def class_s_factory(print_str):
  def add_print_something(cls):
     def print_something(self):
       super(cls, self).print_something()
       print('I am a method defined in ClassS')
       print(print_str)
     setattr(cls, 'print_something', print_something)

  cls = type('ClassS', (ClassA, ), {})
  add_print_something(cls)
  return cls

# Get a string from the database (for example)
print_str_database = 'I am a string from the database'

test_class = class_s_factory(print_str_database)
test_instance = test_class()
test_instance.print_something()

然而,原则上可以有更好的方法来获得同样的结果。你知道吗

相关问题 更多 >