在循环中声明几个python类?

时间:2018-01-03 13:44:37

标签: python

我有一个通用的类定义,就像这样 -

class Foo(object):
    property = 1
    def __init__(self, ...):
    ...

我希望创建大量的类,每个类具有不同的property值,并将这些类存储在列表中。此列表中的类随后将用于创建多个对象。

这样做的最佳方式是什么?

4 个答案:

答案 0 :(得分:2)

虽然我怀疑没有更好的解决方案来解决您的潜在问题,但您可以使用type动态创建类:

class Foo(object):
  def __init__(self, x):
    self.x = x

#  class-name---vvvvvvvvvvvvvvvvv          vvvvvvvvvvvvvvv--class-attributes  
klasses = [type('Foo{}'.format(n), (Foo,), {'property': n}) for n in range(5)]
#                   parent-classes ^^^^^^

klasses[4]
# <class '__main__.Foo4'>

klasses[4].property
# 4

inst = klasses[4]('bar')
inst.x
# 'bar'

答案 1 :(得分:1)

c = []
for i in range(5):
  class X(object):
    property = i
    def __init__(self):
      print(self.property)
  c.append(X)

c[0]()  # will print 0
c[4]()  # will print 4

但这有一些缺点。我也认为这个问题下面给出的评论非常值得注意。很可能你会争取一个对你原来的问题不是最好的解决方案。

答案 2 :(得分:-1)

如果您真的想这样做,那么请确保您可以使用type

动态创建类
class BaseClass(object):
    # the code that needs to be common among all classes

properties = [1, 2, 3]
classes = [type("class_{0}".format(i), (BaseClass,), {'property': property}) for i, property in enumerate(properties)]

但是,您可能需要考虑您的设计。我不知道你想要解决的问题,但是将属性变量保持为实例可能更有意义。

答案 3 :(得分:-2)

我认为最好的方法就是将i = 0迭代到n-1,将新对象附加到列表的末尾。然后,您可以使用i索引到列表中并以此方式更改property的值。