41841

Object initializer syntax (c#) in python?

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

Answer1:

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

Answer2:

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}!")

<strong>Update 2017</strong> 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.

Answer3:

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

Recommend

  • Conditional format html table rows with python
  • Passing String, integer and tuple information as key for python dictionary
  • Represent a table as object
  • Runtime injection of attributes into module namespace
  • Why does sphinx format my docstring parameters on the same line
  • Can I overwrite the string form of a namedtuple?
  • How to avoid the redefinition of a function (PEP8 error F811)
  • BigQuery not dealing with timestamp in millisecond with partition column
  • Why nullable types will not be equal in this case?
  • Specify datetime format for WCF Data Service
  • How can I export a gbm model in R?
  • Controlling volume of running applications in Mac OS X via Objective-C
  • Entity Framework Core 2.0 add-migration not generating anything
  • SAXReader not re-ecape characters
  • Insert new calendar with SyncAdapter- Calendar API Android
  • Django simple Captcha “No module named fields” error
  • Can I check if a recipient has an automatic reply before I send an email?
  • QLineEdit password safety
  • Nant, Vault & Windows Integrated Authentication
  • C# - Serializing and deserializing static member
  • Bug in WPF DataGrid
  • Incrementing object id automatically JS constructor (static method and variable)
  • jQuery tmpl and DataLink beta
  • How can I estimate amount of memory left with calling System.gc()?
  • Why winpcap requires both .lib and .dll to run?
  • align graphs with different xlab
  • Return words with double consecutive letters
  • Cannot Parse HTML Data Using Android / JSOUP
  • Python: how to group similar lists together in a list of lists?
  • Java static initializers and reflection
  • Bitwise OR returns boolean when one of operands is nil
  • unknown Exception android
  • sending mail using smtp is too slow
  • Busy indicator not showing up in wpf window [duplicate]
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • Reading document lines to the user (python)
  • Observable and ngFor in Angular 2
  • How can I use `wmic` in a Windows PE script?
  • Unable to use reactive element in my shiny app
  • Python/Django TangoWithDjango Models and Databases