Skip to content Skip to sidebar Skip to footer

Function To Set Properties Of An Object Of A Class Composition

I would like construct a class composition that includes a function set_props for setting the instance variables of components. The application for this is in defining new objects

Solution 1:

Here is what I would do

class Room:
    def __init__(self, kw_door=None, kw_window=None, kw_wall=None):
        if kw_door:
            self.door = Door(**kw_door)
        else:
            self.door = Door()
        if kw_window:
            self.window = Window(**kw_window)
        else:
            self.window = Window()
        if kw_wall:
            self.wall = Wall(**kw_wall)
        else:
            self.wall = Wall()

effectively you are accepting a dictionary that will be unpacked into the instance creation, and when the class definition gets new attributes, they too will be unpacked if they are found in the passed dictionary.


Solution 2:

To answer you first question. If you want to set window attribute of r and kw attribute of that `windows as in your example, you cat do the following:

setattr(getattr(r, "window"), kw, kwargs[kw])

You get attribute named window of r. And for that windows attributes set its own whose name is in variable kw to a new value from kwargs[kw]. As your line has attempted.

But to be perfectly honest, why a function with many possible arguments would be preferred over just accessing/setting the attributes themselves? Or in other words, on the face of it, it looks more complicated then it needs to be.

As for you second question. You should be also able to just use dir() to get list of instance attributes, but yes, inherited attributes will be getting in your way and I am not immediately sure if there is an elegant way around it (i.e. not walk the inheritance tree and do the pruning yourself). But if you genuinely wanted to dynamically walk attributes of an instance that are subject to for instance setting through a function, I'd say add a (class) attribute defining what those are to be for each type rely on that as a defined interface.


side note: There is only one instance of None (and True and False) and it can be tested for identity (not just equality) and since it reads a little better you would normally see if somevar is not None instead of if not somevar == None.


Post a Comment for "Function To Set Properties Of An Object Of A Class Composition"