将类作为没有静态方法和类方法的函数调用并实例化

问题描述 投票:0回答:1

与函数不同的此类可以具有已初始化的内部变量。变量是内部变量这一事实使它更加有序,并且初始化效率更高。

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)

python function class
1个回答
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)
{...}

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) {...}
© www.soinside.com 2019 - 2024. All rights reserved.