【发布时间】:2011-08-09 14:26:14
【问题描述】:
我正在读取一些数据,我想从中创建类 - 这是在加载时完成的。这些类被分组到一个Special 类中,该类只能使用运行时信息进行实例化。这些类依赖于这个Special 类,因此它们只有在创建后才有用。这是一些简化的代码,显示了我希望它如何工作,使用 random 而不是实际的运行时信息:
import random
def make_foo(param1, param2):
class Foo:
def __init__(self, special):
self.param1 = param1
self.param2 = param2
self.special = special
def do(self):
print "%s is doing" % self
def __str__(self):
return "Foo<%s,%s with %s>" % (self.param1, self.param2,
self.special)
return Foo
def make_bar(foo):
class Bar:
def __init__(self, special):
self.foo = foo(special)
def do(self):
print "%s is doing" % (self,)
def __str__(self):
return "Bar<%s>" % self.foo
return Bar
def make_grouper(foobars):
class Grouper:
def __init__(self, special):
self.foobars = [foobar(special) for foobar in foobars]
return Grouper
def make_special(howtomake, groups):
class Special:
def __init__(self):
self.important = random.choice(howtomake)
self.groups = [group(self) for group in groups]
def __str__(self):
return "Special<%s>" % self.important
return Special
Foo10_20 = make_foo(10, 20)
Foo30_40 = make_foo(30, 40)
Bar = make_bar(Foo10_20)
Grouper1 = make_grouper([Foo10_20, Foo30_40])
Grouper2 = make_grouper([Bar, Bar])
Special = make_special("IMPORTANTINFO", [Grouper1, Grouper2])
s = Special()
s.groups[0].foobars[0].do()
s.groups[0].foobars[1].do()
s.groups[1].foobars[0].do()
s = Special()
s.groups[0].foobars[0].do()
s.groups[0].foobars[1].do()
s.groups[1].foobars[0].do()
样本输出:
Foo<10,20 with Special<O>> is doing
Foo<30,40 with Special<O>> is doing
Bar<Foo<10,20 with Special<O>>> is doing
Foo<10,20 with Special<I>> is doing
Foo<30,40 with Special<I>> is doing
Bar<Foo<10,20 with Special<I>>> is doing
可以概括为必须创建一组需要绑定到special 参数的类(因此所有构造函数,一旦类完成,只需使用special 参数)。这可以使用元类更优雅地完成吗,或者这段代码是否可以正常使用?
【问题讨论】:
标签: python metaprogramming metaclass