10

类工厂函数中的一个问题(流畅的python书中的例子)

这是流畅的python一书中关于类工厂函数的代码:

    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__)
return type(cls_name,(object,),cls_attrs)
Dog=factory('Dog','name weight owner')
dog=Dog('rex',30,'sunshuofeng')
print(dog)

我在运行时其报错了:

    Traceback (most recent call last):
 File "C:\Users\18022863809\Desktop\python_work\11.py", line 27, in <module>
Dog=factory('Dog','name weight owner')
File "C:\Users\18022863809\Desktop\python_work\11.py", line 26, in factory
return type(cls_name,(object,),cls_attrs)
TypeError: __slots__ must be identifiers

这是为什么?

查看全部
weixin_43378698
永不秃头的ssf
2019/01/22 16:38
  • python
  • 点赞
  • 收藏
  • 回答
    私信
满意答案
查看全部

1个回复