Skip to content Skip to sidebar Skip to footer

Creating Python Classes With Arbitrarily Substituted Attribute Name

I apologize for not giving this question a better title; the reason that I am posting it is that I don't even have the correct terminology to know what I am looking for. I have def

Solution 1:

Here is a way to get the effect I think you want.

Define a generic class with a generic attribute name. Then in each sub class follow the advice in http://docs.python.org/reference/datamodel.html#customizing-attribute-access to make the attribute look externally like it is called whatever you want it called.

Your description of what you do feels like it has a "code smell" to me, I'd suggest reviewing your design very carefully to see whether this is really what you want to do. But you can make it work with my suggestion.

Solution 2:

You can also create a super-class with all common stuff and then sub-classes with specific attributes.

Or even:

defSuperClass(object):
    specific_attribute = 'unset'def__init__(self, arg):
        setattr(self, specific_attribute, arg)

    def__str__(self):
        returngetattr(self, specific_attribute)


defEggClass(SuperClass):
    specific_attribute = 'eggs'

Solution 3:

Have you considered not overcomplicating things and just create one class? (since they are identical anyway)

classFoodClass(object):def__init__(self, foodname, arg):
        self.attrs = {foodname: arg}
        self.foodname = foodname

    def__str__(self):
        returnself.attrs[foodname]

If you want some nice constructors, just create them separately:

def make_eggs(arg):
    return FoodClass('eggs', arg)

def make_spam(arg):
    return FoodClass('spam', arg)

Solution 4:

To create attributes during runtime, just add them in self.__dict__['foo'] = 'I'm foo' in the class code.

Post a Comment for "Creating Python Classes With Arbitrarily Substituted Attribute Name"