Python 在for循环中创建子类
我有以下代码:Python 在for循环中创建子类,python,python-3.x,class,Python,Python 3.x,Class,我有以下代码: class test(): def __init__(self): def tt(self, dic): for value, item in dic: setattr(self, item, value) lar = {'a': 2, 'b': 3} lbr = {'c': 4, 'd': 8} lcr = {'e': 5, 'f': 0}
class test():
def __init__(self):
def tt(self, dic):
for value, item in dic:
setattr(self, item, value)
lar = {'a': 2, 'b': 3}
lbr = {'c': 4, 'd': 8}
lcr = {'e': 5, 'f': 0}
dic = {'ar': lar, 'br': lbr, 'lcr': lcr}
for value, item in dic:
setattr(self, item, tt(self.item, value))
rrr = test()
print(rrr.ar.gg)
我想知道我是否能做到这一点,我需要在另一个项目中使用函数“tt”,但放在这里太重了,想法保持不变
我需要从for循环中的函数生成子类
class Data(object):
def __init__(self, **data):
for k, v in data.items():
setattr(self, k, v)
class Test(object):
def __init__(self):
kwmap = {
'ar': {'a': 2, 'b': 3},
'br': {'c': 4, 'd': 8},
'cr': {'e': 5, 'f': 0}
}
for attrname, kw in kwmap.items():
setattr(self, attrname, Data(**kw))
rrr = Test()
print(rrr.ar.b) # should output 3
注意:我从测试中提取了数据类。uuu init_uuuuuuu,因为它不依赖于测试中的任何局部变量。uuu init_uuuuuuuuuuu,但是您当然可以在任何您认为合适的地方声明-请记住,在函数中具有类定义意味着每次调用函数时都会创建一个新的类对象,这是对资源的浪费,并且会破坏任何基于类标识的测试
NB2:如果您需要对象属于不同的类,那么只需将类放入映射中即可-python类本身就是对象,就像函数、模块等:
class A(object):
def __init__(self, a, b):
self.a = a
self.b = b
class B(object):
def __init__(self, c, d):
self.c = c
self.d = d
class C(object):
def __init__(self, e, f):
self.e = e
self.f = f
class Test2(object):
def __init__(self, specs):
for attrname, (cls, kw) in specs.items():
setattr(self, attrname, cls(**kw))
test2 = Test2({
'ar': (A, {'a': 2, 'b': 3}),
'br': (B, {'c': 4, 'd': 8}),
'cr': (C, {'e': 5, 'f': 0})
})
print(test2.ar.b) # should output 3
嵌套函数的意义是什么?我有很多数据,希望以此方式组织它x属性的类型或类别是什么?放在这里太重了-你能解释一下你的意思吗?这看起来像一个XY问题。您是否希望创建一个测试对象,该测试对象包含在ar、br、cr字段中的另外3个测试对象,每个字段的gg==3?对不起,我第一次更新了我不想澄清的问题