Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 686
SacredGeometry Avatar asked Jun 24 '13 19:06

SacredGeometry


People also ask

What is object syntax in C#?

C# - Object Initializer Syntax C# 3.0 (. NET 3.5) introduced Object Initializer Syntax, a new way to initialize an object of a class or collection. Object initializers allow you to assign values to the fields or properties at the time of creating an object without invoking a constructor.

What is new {} in C#?

Use the new keyword to create an instance of the array. The new operator is used to create an object or instantiate an object. Here in the example an object is created for the class using the new.

How do you initialize an object in C sharp?

You can use object initializers to initialize type objects in a declarative manner without explicitly invoking a constructor for the type.


2 Answers

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
like image 162
jh314 Avatar answered Oct 31 '22 18:10

jh314


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.

like image 39
Max Shenfield Avatar answered Oct 31 '22 20:10

Max Shenfield