Sharing attributes among objects that can be used in decorated methods

I have a group of objects which are instances of the same class. I would like them to share a common attribute. Ok, I can simply define a class attribute:

MyClass():
    classattr = None

    def __init__(self):
        self.instattr = None

but, I want to make another group of objects using the same class with the common attribute set to something else than the first group.

I need this attribute within the class so I can decorate methods as properties, while still using that attribute within the property method.

Is there any way to do this?

Answers


You could make the class attribute a dictionary; each 'group' of instances is given it's own key in that dictionary:

class MyClass():
    classattr_groups = {'group1': None, 'group2': None}

The whole object is still shared among instances, but you'd use one of the keys for one group of instances, another for a second group, etc.

Another approach is to subclass; give each group its own derived class and own class attribute:

class MyClass():
    classattr = None


class MyClassGroup1(MyClass):
    classattr = 'group1'


class MyClassGroup2(MyClass):
    classattr = 'group2'

Need Your Help

Telerik and jQuery : RadGrid and Fancybox

c# fancybox telerik-grid

I am using telerik radgrid to show images and using jquery fancybox to popup the image at user control (ascx file).

Classifying Single Instance in Weka

machine-learning classification weka prediction decision-tree

I trained and created a J48 model using WEKA gui. I saved the model file to my computer and now I would like to use it to classify a single instance in my Java code. I would like to get a predictio...