与函数不同的此类可以具有已初始化的内部变量。 变量是内部变量这一事实使它更加有序,并且初始化效率更高。
import re
class clean_ship_to:
pattern_num_int = re.compile(r'[\W\_]+') # initialized internal variable
@classmethod
def clean(cls, ship_to):
ship_to['num_int'] = cls.pattern_num_int.sub('', ship_to['num_int'])[:35]
ship_to['contact_name'] = ship_to['contact_name'][:35]
ship_to['contact_phone'] = ship_to['contact_phone'][:25]
return ship_to
这可以用clean_ship_to.clean(ship_to)
来调用,我要clean_ship_to(ship_to)
答案 0 :(得分:0)
class clean_ship_to(dict):
"""
Clean dict ship_to
"""
# dict inheritance fix pylint(unsubscriptable-object) alert
pattern_num_int = re.compile(r'[\W\_]+')
def __new__(cls, ship_to):
ship_to['num_int'] = cls.pattern_num_int.sub('', ship_to['num_int'])[:35]
ship_to['contact_name'] = ship_to['contact_name'][:35]
ship_to['contact_phone'] = ship_to['contact_phone'][:25]
return ship_to
>>> clean_ship_to(ship_to)
{...}