class instance customization

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Apr 18 05:23:56 EDT 2010


On Sat, 17 Apr 2010 19:55:44 +0400, Alexander wrote:
 
> Ok, I'll try to explain on the following example. Let's consider class
> MyClass that holds one string and concatenate it with other not defined
> in this class:
[...]
> and with working application:
> 
> a = MyClass()
> a.set('key1')
> 
> b1 = a.new('value1')
> b2 = a.new('value2')
> 
> print b1, "," ,b2 # give 'key1 value1 , key1 value2'
> 
> a.set('key2')
> 
> print b1, ",", b2 # give 'key2 value1 , key2 value2'

Looking at your design, I can't see any reason for SubClass to be a 
subclass of MyClass. It doesn't inherit any behaviour, and the 
constructor takes completely different arguments. Why make it a Subclass?

MyClass is dangerous: creating an instance doesn't fully initialise the 
instance, it leaves it in a half-initialised state that can cause 
exceptions from simple operations like:

instance = MyClass()
print instance

This is very bad design.

Redesigning the pair of classes, I get this:

class MyClass(object):
    def __init__(self, key):
        self.key = key  # No obvious need to make key a private attribute.
    def new(self, value):
        return AnotherClass(self, value)

class AnotherClass(object):
    def __init__(self, obj, value):
        self.obj = obj
        self.value = value
    def __str__(self):
        return "%s %s" % (self.obj.key, self.value)


which gives the behaviour you ask for:

>>> a = MyClass('key1')
>>> b1 = a.new('value1')
>>> b2 = a.new('value2')
>>> print b1, "," ,b2
key1 value1 , key1 value2
>>>
>>> a.key = 'key2'
>>> print b1, "," ,b2
key2 value1 , key2 value2



-- 
Steven



More information about the Python-list mailing list