Hey, I just started wondering about this as I came upon a code that expected an object with a certain set of attributes (but with no specification of what type this object should be).
One solution would be to create a new class that has the attributes the code expects, but as I call other code that also needs objects with (other) attributes, I'd have to create more and more classes.
A shorter solution is to create a generic class, and then set the attributes on instances of it (for those who thought of using an instance of object
instead of creating a new class, that won't work since object
instances don't allow new attributes).
The last, shortest solution I came up with was to create a class with a constructor that takes keyword arguments, just like the dict
constructor, and then sets them as attributes:
class data: def __init__(self, **kw): for name in kw: setattr(self, name, kw[name]) options = data(do_good_stuff=True, do_bad_stuff=False)
But I can't help feeling like I've missed something obvious... Isn't there a built-in way to do this (preferably supported in Python 2.5)?
Python provides a function setattr() that can easily set the new attribute of an object. This function can even replace the value of the attribute. It is a function with the help of which we can assign the value of attributes of the object.
An instance/object attribute is a variable that belongs to one (and only one) object. Every instance of a class points to its own attributes variables. These attributes are defined within the __init__ constructor.
An instance attribute is a Python variable belonging to one, and only one, object. This variable is only accessible in the scope of this object and it is defined inside the constructor function, __init__(self,..) of the class.
type('', (), {})()
will create an object that can have arbitrary attributes.
Example:
obj = type('', (), {})() obj.hello = "hello" obj.world = "world" print obj.hello, obj.world # will print "hello world"
type()
with three arguments creates a new type.
The first argument ''
is the name of the new type. We don't care about the name, so we leave it empty.
The second argument ()
is a tuple of base types. Here object
is implicit.
The third argument is a dictionary of attributes of the new object. We start off with no attributes so it's empty {}
.
In the end we instantiate a new instance of this new type with ()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With