什么是定义课程的更好方法'带有可选关键字参数的__init__方法?

时间:2015-01-01 16:26:15

标签: python python-3.x

我希望课程的内容与以下相同:

class Player:
    def __init__(self, **kwargs):
        try:
            self.last_name = kwargs['last_name']
        except:
            pass
        try:
            self.first_name = kwargs['first_name']
        except:
            pass
        try:
            self.score = kwargs['score']
        except:
            pass

但这看起来真的很草率。有没有更好的方法来定义 __ init __ 方法?我希望所有的关键字参数都是可选的。

6 个答案:

答案 0 :(得分:11)

如果你只有3个关键字args,那么这会更好。

class Player:

    def __init__(self, last_name=None, first_name=None, score=None):
        self.last_name = last_name
        self.first_name = first_name
        self.score = score

答案 1 :(得分:10)

如果你只有3个参数,那么Bhargav Rao的解决方案更合适,但如果你有很多潜在的论点,那么试试:

class Player:
    def __init__(self, **kwargs):
        self.last_name = kwargs.get('last_name')
        # .. etc.

kwargs.get('xxx')将返回xxx密钥(如果存在),如果不存在则返回None。 .get采用可选的第二个参数,如果xxx不在kwargs(而非None),则返回该参数,例如要将属性设置为空字符串,请使用kwargs.get('xxx', "")

如果您确实希望该属性未定义(如果该属性不在kwargs中,那么这将执行此操作:

class Player:
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

这将是令人惊讶的行为所以我建议不要这样做。

答案 2 :(得分:4)

这是实现此目标的一种方式,可以轻松更改:

class Player:
    _VALID_KEYWORDS = {'last_name', 'first_name', 'score'}

    def __init__(self, **kwargs):
        for keyword, value in kwargs.items():
            if keyword in self._VALID_KEYWORDS:
                setattr(self, keyword, value)
            else:
                raise ValueError(
                    "Unknown keyword argument: {!r}".format(keyword))

样本用法:

Player(last_name="George", attitude="snarky")

结果:

Traceback (most recent call last):
  File "keyword_checking.py", line 13, in <module>
    Player(last_name="George", attitude="snarky")
  File "keyword_checking.py", line 11, in __init__
    raise ValueError("Unknown keyword argument: {!r}".format(keyword))
ValueError: Unknown keyword argument: 'attitude'

答案 3 :(得分:3)

您可以使用keyword arguments

class Player:

    def __init__(self, last_name=None, first_name=None, score=None):
        self.last_name = last_name
        self.first_name = first_name
        self.score = score

obj = Player('Max', 'Jhon')
print obj.first_name, obj.last_name


Jhon Max

使用参数 **kwargs

class Player:
    def __init__(self, **args):

        self.last_name = args.get('last_name')

        self.first_name = args.get('first_name')

        self.score = args.get('score', 0) # 0 is the default score.

obj = Player(first_name='Max', last_name='Jhon')

print obj.first_name, obj.last_name, obj.score


Max Jhon 0

答案 4 :(得分:0)

我可以尝试这种方式:

#!/usr/bin/python

class Player(object):
    def __init__(self, **kwargs):
        for key, val in kwargs.items():
            self.__dict__[key] = val

obj = Player(first_name='First', last_name='Last')
print obj.first_name
print obj.last_name

newobj = Player(first_name='First')
print newobj.first_name

输出:

First
Last
First

答案 5 :(得分:0)

这取决于你想要的最终结果。如果要创建一个在字典中定义属性的类,可以使用setattr。

class Player:
    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)             


In [1]: player = Player(first_name='john', last_name='wayne', score=100)

In [2]: player.first_name
Out[2]: 'john'

In [3]: player.last_name
Out[3]: 'wayne'

In [4]: player.score
Out[4]: 100

In [5]: player.address
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-6-0f7ee474d904> in <module>()
----> 1 player.address

AttributeError: 'Player' object has no attribute 'address'