Python 3对象构造:哪种是最Pythonic /公认的方式? [英] Python 3 object construction: which is the most Pythonic / the accepted way?

查看:99
本文介绍了Python 3对象构造:哪种是最Pythonic /公认的方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中有一个非常冗长而严格的背景,我发现能够对Python对象进行突变,使其具有除提供给构造函数的字段之外的其他字段,这确实是丑陋的。

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 constructor really "ugly".

试图习惯于Python的思维方式,我想知道如何允许构造对象

Trying to accustom myself to a Pythonic way of thinking, I'm wondering how I should allow my objects to be constructed.

我的直觉是必须在构造时传递字段,例如:

My instinct is to have to pass the fields at construction time, such as:

def __init__(self, foo, bar, baz=None):
    self.foo = foo
    self.bar = bar
    self.baz = baz

但这可能变得过于冗长,并且使许多字段难以通过。为了克服这个问题,我认为最好的方法是将一本字典传递给构造函数,然后从中提取字段

But that can become overly verbose and confusing with many fields to pass. To overcome this I assume the best method is to pass one dictionary to the constructor, from which the fields are extracted:

def __init__(self, field_map):
    self.foo = field_map["foo"]
    self.bar = field_map["bar"]
    self.baz = field_map["baz"] if baz in field_map else None

我能想到的另一种机制是在其他地方添加了字段,例如:

The other mechanism I can think of is to have the fields added elsewhere, such as:

class Blah(object):

    def __init__(self):
        pass

...

blah = Blah()
blah.foo = var1

但这对我来说感觉太松了。

But as that feels way too loose for me.

(我想我的问题是如何处理Python中的接口 ...)

(I suppose the issue in my head is how I deal with interfaces in Python...)

因此,重申一下这个问题:我应该如何在Python中构造对象?

So, to reiterate the question: How I should construct my objects in Python? Is there an accepted convention?

推荐答案

您所描述的第一个很常见。有些人使用较短的

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']
       #..

允许创建对象像

t = Thing(something=1)

可以进一步修改为

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

允许

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

如Debilski在评论中指出,最后一种方法是有点不安全,您可以像这样添加可接受的参数列表:

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.

这篇关于Python 3对象构造:哪种是最Pythonic /公认的方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆