Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Python shortcut for an __init__ that simply sets properties? [duplicate]

It's sometimes common in Python to see __init__ code like this:

class SomeClass(object):
    def __init__(self, a, b, c, d, e, f, g):
        self.a = a
        self.b = b
        self.c = c
        self.d = d
        self.e = e
        self.f = f
        self.g = g

especially if the class in question is purely a data structure with no behaviour. Is there a (Python 2.7) shortcut for this or a way to make one?

like image 574
naiveai Avatar asked Nov 11 '16 10:11

naiveai


People also ask

Are there constructors in Python?

Class constructors are a fundamental part of object-oriented programming in Python. They allow you to create and properly initialize objects of a given class, making those objects ready to use.

How do you create a class property in Python?

Python property() function returns the object of the property class and it is used to create property of a class. Parameters: fget() – used to get the value of attribute. fset() – used to set the value of attribute.

What is a class type in Python?

type is a metaclass, of which classes are instances. Just as an ordinary object is an instance of a class, any new-style class in Python, and thus any class in Python 3, is an instance of the type metaclass. In the above case: x is an instance of class Foo . Foo is an instance of the type metaclass.

What is type constructor in Python?

What is a Constructor in Python? A constructor can simply be defined as a special type of method or function which can be used to initialize instances of various members in a class.


1 Answers

You could use Alex Martelli's Bunch recipe:

class Bunch(object):
    """
    foo=Bunch(a=1,b=2)
    """
    def __init__(self, **kwds):
        self.__dict__.update(kwds)
like image 67
unutbu Avatar answered Sep 30 '22 18:09

unutbu