<p>您可以这样做,使用<code>globals()</code></p>
<pre><code>classList = ['foo', 'bar', 'baz']
for className in classList:
class Temp:
def __init__ (self, dataFrame):
self.column = dataFrame[className]
def calc ():
return self.column.sum()
Temp.__name__ = className
globals()[className] = Temp
</code></pre>
<p>然后可以执行<code>foo()</code>来创建类<code>foo</code>的对象。对于实际示例,您必须使用<code>__init__</code>方法所需的参数进行调用。这只是为了证明它是有效的</p>
<pre><code>print(type(foo()).__name__) # foo
print(type(bar()).__name__) # bar
print(type(baz()).__name__) # baz
</code></pre>
<p>如果您想更改类名,那么您可以这样做</p>
<pre><code>Temp.__name__ = f'{className}_calc'
globals()[f'{className}_calc'] = Temp
</code></pre>
<p>正如wim在评论中指出的,您还需要设置<code>__qualname__</code><code>Temp.__qualname__ = f'{className}_calc'</code></p>
<p>编辑:</p>
<p>由于类的方法中的名称查找是在运行时(而不是在编译时)执行的,因此代码段有一个bug<code>className</code>将始终引用<code>classList</code>(<code>baz</code>)中的最后一个元素。在本例中,此名称存在于循环范围之外,并且将是所有类的方法中<code>className</code>的值。(例如:<code>self.column = dataFrame[className]</code>)<;-这总是<code>dataFrame['baz']</code></p>
<p>要解决这个问题,必须声明一个名为<code>className</code>的类级变量,并将<code>className</code>(循环中的变量)赋值给该变量。因此,在编译时,该值将绑定到类。类的方法中对<code>className</code>的所有引用都需要更改为<code>self.className</code>,代码才能按预期工作</p>
<pre><code>class Temp:
className = className # note this line
def __init__ (self, dataFrame):
self.column = dataFrame[self.className] # and this line with the original snippet
</code></pre>