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

Posted

技术标签:

【中文标题】将方法添加到调用“super”的动态创建的类【英文标题】:Add method to dynamically created class that calls 'super' 【发布时间】:2014-05-20 00:19:53 【问题描述】:

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

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

# 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

我尝试了一些我提出的答案。它有效,但是有没有更好的方法来处理这种情况?

【问题讨论】:

【参考方案1】:

这是我最终尝试的方法,并且有效:

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()

但是,原则上可能存在获得相同结果的更好方法。

【讨论】:

我认为人们对您答案的措辞有点困惑,因为我们看到很多人使用答案来回答问题的延续。我已经调整了措辞,以更清楚地表明这确实是对您问题的回答。

以上是关于将方法添加到调用“super”的动态创建的类的主要内容,如果未能解决你的问题,请参考以下文章

cglib动态代理之原理说明

WebService的创建和部署以及通过反射动态调用WebService

动画期间未调用 UIButton 的选择器方法

对于自定义Dialog需调用啥方法将动态创建的视图dialogview显示到Dialog上?

使用JQuery将文本添加到动态创建的HTML表中

向动态创建的表行添加按钮