使用函数创建类:传递参数

2024-04-19 04:58:48 发布

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

def cclass(arg1):
...     if True:
...         class klass (object):
...             print arg1
...             def __init__(self,arg1):
...                 self.arg1=arg1
...             def klassfunc(self):
...                 arg2=self.arg1
...                 print arg2
...     return klass()

此代码自然会生成错误消息:

>>> test=cclass('astring')
astring
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
  File "<interactive input>", line 10, in cclass
TypeError: __init__() takes exactly 2 arguments (1 given)

我的问题是:如何将函数arg1传递给类?你知道吗


Tags: inselfinputifinitdeflineinteractive