7

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

4
  • It's even better with var: var myObject = new .... Commented Jun 24, 2013 at 19:56
  • 1
    Changed from Object to SomeClass because in its original form, that was a compiler error. Commented Jun 24, 2013 at 19:58
  • It was c#-like pseudo code but ok :) Commented Jun 24, 2013 at 20:07
  • For arbitrary Python objects (ones you don't control), there isn't a nice syntax. I think the answers below give good suggestions if you do control the object. Commented Dec 21, 2017 at 14:24

3 Answers 3

6

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
Sign up to request clarification or add additional context in comments.

1 Comment

And if you want a "real class" that also has namedtuple behavior, you can inherit from a namedtuple
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.

4 Comments

nice solution. imho, nicer than the namedtuple-thing
Thanks! I think the kwargs are unnecessary since you can specify default arguments right in the functions interface. Going to edit for that, and to mention attrs which can do this automatically.
If I understand properly this would be mutually exclusive with something like sql alchemy, right?
There's an attrs-sqlalchemy integration that gives you equality and comparison operations, as well as a nicer representation.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.