以 Python 方式操作大量关键字参数

发布于 2024-11-20 13:47:16 字数 1168 浏览 4 评论 0原文

我有一个类的 _init_ 函数需要相当多的关键字参数。我希望能够基本上重写这段代码,使其在语法上更清晰(更少的硬编码)。最好我希望能够获得它,以便只需向 _init_ 添加关键字参数即可分别更改 null 函数中的所有属性/参数。

class Class :

    def __init__ (self, kw0=0, kw1=1, kw2=2) :

        ''' The keyword arguments as strings. '''
        self.Keys = ['kw0', 'kw1', 'kw2']

        ''' Their values. '''
        self.Values = [kw0, kw1, kw2]

        ''' A dictionary made from the keys and values. '''
        self.Dict = self.make_dict()

        ''' As individual attributes, '''
        self.KW0, self.KW1, self.KW2 = self.Values

    def make_dict (self) :
        ''' Makes a dictionary '''

        keys   = self.Keys
        values = self.Values

        _dict = {}
        for i in xrange(len(keys)) :
            key   = keys[i]
            value = values[i]

            _dict[key] = value

        return _dict

    def null (self, kw0=None, kw1=None, kw2=None) :
        ''' The same keyword arguments as **__init__** but they all default
            to **None**. '''

        pass

c = Class()
print c.Keys
print c.Values
print c.Dict
print c.KW0
print c.KW1
print c.KW2

I have a class who's _init_ function requires quite a few keyword arguments. I'd like to be able to basically rewrite this bit of code so that it's syntactically cleaner (less hard coding). Preferably I'd like to be able to get it so that simply adding a keyword argument to _init_ would change all the attributes/arguments in the null function respectively.

class Class :

    def __init__ (self, kw0=0, kw1=1, kw2=2) :

        ''' The keyword arguments as strings. '''
        self.Keys = ['kw0', 'kw1', 'kw2']

        ''' Their values. '''
        self.Values = [kw0, kw1, kw2]

        ''' A dictionary made from the keys and values. '''
        self.Dict = self.make_dict()

        ''' As individual attributes, '''
        self.KW0, self.KW1, self.KW2 = self.Values

    def make_dict (self) :
        ''' Makes a dictionary '''

        keys   = self.Keys
        values = self.Values

        _dict = {}
        for i in xrange(len(keys)) :
            key   = keys[i]
            value = values[i]

            _dict[key] = value

        return _dict

    def null (self, kw0=None, kw1=None, kw2=None) :
        ''' The same keyword arguments as **__init__** but they all default
            to **None**. '''

        pass

c = Class()
print c.Keys
print c.Values
print c.Dict
print c.KW0
print c.KW1
print c.KW2

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

千年*琉璃梦 2024-11-27 13:47:17

这是我喜欢 python 的一件事。在您的 __init__ 中,

def __init__ (self, **kwargs):
    self.__dict__.update(kwargs)

会将字典中定义的那些成员 kwargs 附加为类的成员。

编辑 - 反映 **kwargs 的正确语法,并 update() 而不是 append()

This is one thing I love about python. In your __init__

def __init__ (self, **kwargs):
    self.__dict__.update(kwargs)

Will append those members defined in a dictionary kwargs as members of the class.

EDITED - to reflect proper syntax for **kwargs, and update() instead of append()

又怨 2024-11-27 13:47:17

为什么不接受任何关键字参数。您可以使用类属性来表示允许的关键字名称及其默认值。

class Class(object):

     _defaults = dict(kw0=42, kw1=None, kw2=True, kw3="Ni!")

     def __init__(self, **kwargs):

        # Raise exception if any non-supported keywords supplied
        if set(kwargs.keys()) - set(self._defaults.keys()):
            raise KeyError("unsupported keyword argument")

        # Update our instance with defaults, then keyword args
        self.__dict__.update(self._defaults)
        self.__dict__.update(kwargs)

如果您希望在多个方法(例如 __init__()null())中实现相同的功能,那么只需将参数处理代码分解为它自己的方法并调用它来自两个地方。

一个缺点是 help() 和其他 Python 文档工具不会显示允许的关键字参数,因为它们不在您的方法签名中。

顺便说一句,我不太清楚为什么你要分开存储键和值。只需将它们存储为字典,然后在需要时使用字典的 .keys().values() 方法获取键或值。

Why not accept any keyword arguments. You can use a class attribute for allowable keyword names and their default values.

class Class(object):

     _defaults = dict(kw0=42, kw1=None, kw2=True, kw3="Ni!")

     def __init__(self, **kwargs):

        # Raise exception if any non-supported keywords supplied
        if set(kwargs.keys()) - set(self._defaults.keys()):
            raise KeyError("unsupported keyword argument")

        # Update our instance with defaults, then keyword args
        self.__dict__.update(self._defaults)
        self.__dict__.update(kwargs)

If you want the same functionality in more than one method (e.g. __init__() and null()) then just break the argument handling code out into its own method and call it from both places.

One downside is that help() and other Python documentation tools won't show the allowable keyword arguments, since they aren't in your method signature.

As an aside, I'm not quite sure why you're storing keys and values separately. Just store them as a dictionary, then get the keys or values when you want them using the dictionary's .keys() or .values() method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文