それはあなたが探しているものですか?
# Generic class definition
class Generic (object):
value = None
@classmethod
def val(cls):
return int(cls.value)
# Top level class
TopLevelClass = type('TopLevelClass',
(Generic, ), {})
lines = ["A B C 42",
"A B D 43"]
for line in lines:
# Parse the line
path = line.split()[:-1]
value = line.split()[-1]
# Create the classes
current = TopLevelClass
for x in path:
if hasattr(current,x):
current = getattr(current,x)
else:
cls = type(x, (Generic, ), {})
setattr(current,x,cls)
current = cls
# Apply value
setattr(cls,'value',value)
# Test
print(TopLevelClass.A.B.C.val())
print(TopLevelClass.A.B.D.val())
出力:
>>> 42
>>> 43