def factory(cls_name,field_name):
try:
field_name=field_name.replace(',',' ').spilt(' ')
except AttributeError:
pass
field_name=tuple(field_name)
def __init__(self,*args,**kwargs):
attrs=dict(zip(self.__slots__,args))
attrs.update(kwargs)
for name,value in attrs.items():
setattr(self,name,value)
def __iter__(self):
for name in self.__slots__:
yield getattr(self,name)
def __repr__(self):
values=','.join('{}={!r}'.format(*i) for i in zip(self.__slots__,self))
return '{}({})'.format(self.__class__.__name__,values)
cls_attrs=dict(__slots__=field_name,__init__=__init__,__iter__=__iter__,__repr__=__repr__) #l类属性字典
return type(cls_name,(object,),cls_attrs) #构造新类
Dog=factory('Dog','name weight owner')
dog=Dog('rex',30,'sunshuofeng')
print(dog)
报错原因是TypeError: __slots__ must be identifiers
这是为什么啊
try:
field_name=field_name.replace(',',' ').spilt(' ')
except AttributeError:
pass
field_name=tuple(field_name)
def __init__(self,*args,**kwargs):
attrs=dict(zip(self.__slots__,args))
attrs.update(kwargs)
for name,value in attrs.items():
setattr(self,name,value)
def __iter__(self):
for name in self.__slots__:
yield getattr(self,name)
def __repr__(self):
values=','.join('{}={!r}'.format(*i) for i in zip(self.__slots__,self))
return '{}({})'.format(self.__class__.__name__,values)
cls_attrs=dict(__slots__=field_name,__init__=__init__,__iter__=__iter__,__repr__=__repr__) #l类属性字典
return type(cls_name,(object,),cls_attrs) #构造新类
Dog=factory('Dog','name weight owner')
dog=Dog('rex',30,'sunshuofeng')
print(dog)
报错原因是TypeError: __slots__ must be identifiers
这是为什么啊