Object initializer syntax (c#) in python?

孤人 提交于 2019-12-12 16:00:11

问题


I was wondering if there is a quick way to initialise an object in python.

For example in c# you can instantiate an object and set the fields/properties like...

SomeClass myObject = new SomeClass() { variableX = "value", variableY = 120 };

Thanks

Brian


回答1:


If you want a quick dirty object with some fields, I highly suggest using namedtuples

from collections import namedtuple
SomeClass = namedtuple('Name of class', ['variableX', 'variableY'], verbose=True)
myObject = SomeClass("value", 120)

print myObject.variableX



回答2:


If you control the class, you can implement your own by making each public field settable from the comstructor, with a default value Here's an example (in Python3) for an object with foo and bar fields:

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

We can instantiate the class above with a series of named arguments corresponding to the class values.

thing = MyThing(foo="hello", bar="world")

# Prints "hello world!"
print("{thing.foo} {thing.bar}!")

Update 2017 The easiest way to do this is to use the attrs library

import attr

@attr.s
class MyThing:
    foo = attr.ib()
    bar = attr.ib()

Using this version of MyThing just works in the previous example. attrs gives you a bunch of dunder methods for free, like a constructor with defaults for all public fields, and sensible str and comparison functions. It all happens at class definition time too; zero performance overhead when using the class.




回答3:


You could use a namedtuple:

>>> import collections
>>> Thing = collections.namedtuple('Thing', ['x', 'y'])
>>> t = Thing(1, 2)
>>> t
Thing(x=1, y=2)
>>> t.x
1
>>> t.y
2


来源:https://stackoverflow.com/questions/17283957/object-initializer-syntax-c-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!