Python 3 object construction: which is the most Pythonic / the accepted way?

前端 未结 2 1053
时光取名叫无心
时光取名叫无心 2021-02-09 00:35

Having a background in Java, which is very verbose and strict, I find the ability to mutate Python objects as to give them with fields other than those presented to the construc

2条回答
  •  不思量自难忘°
    2021-02-09 01:24

    The first you describe is very common. Some use the shorter

    class Foo:
       def __init__(self, foo, bar):
           self.foo, self.bar = foo, bar
    

    Your second approach isn't common, but a similar version is this:

    class Thing:
       def __init__(self, **kwargs):
           self.something = kwargs['something']
           #..
    

    which allows to create objects like

    t = Thing(something=1)
    

    This can be further modified to

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

    allowing

    t = Thing(a=1, b=2, c=3)
    print t.a, t.b, t.c # prints 1, 2, 3
    

    As Debilski points out in the comments, the last method is a bit unsafe, you can add a list of accepted parameters like this:

    class Thing:
        keywords = 'foo', 'bar', 'snafu', 'fnord'
        def __init__(self, **kwargs):
            for kw in self.keywords:
                setattr(self, kw, kwargs[kw])
    

    There are many variations, there is no common standard that I am aware of.

提交回复
热议问题