class instance customization
jeanmichel at sequans.com
Mon Apr 19 05:32:06 EDT 2010
> On 17.04.2010 18:32, Steven D'Aprano wrote:
>> On Sat, 17 Apr 2010 13:09:43 +0400, Alexander wrote:
>>> Hi, list.
>>> I've some nontrivial class implementation MyClass and its instance my:
>>> my = MyClass(args)
>>> MyClass uses in internals some variable which is not defined in MyClass
>>> itself. I want to extend instance of MyClass at runtime defining this
>>> variable and making new instance. It is like a class inheritance in a
>>> static way
>> I'm afraid I don't understand what you are asking. MyClass uses a
>> variable which is not defined in MyClass. Where is it defined? Is it a
>> global variable?
>> What do you mean, "like a class inheritance in a static way"?
>> Perhaps you should give an example of what you want to happen.
> 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:
> class MyClass(object):
> def __init__(s): pass
> def set(s, key):
> s.__key = key
> def __str__(s):
> return s.__key + ' ' + s.__other
> def new(s, value):
> return SubClass(s, value)
> The problem is how to implement class SubClass which inherits MyClass,
> define new variable __other accessible from MyClass intance and with
> working application:
> a = MyClass()
> b1 = a.new('value1')
> b2 = a.new('value2')
> print b1, "," ,b2 # give 'key1 value1 , key1 value2'
> print b1, ",", b2 # give 'key2 value1 , key2 value2'
Unfortunately I'm not sure you description clarifies anything.
My *guess* is that you would need a Factory class.
class Factory: # this is a Factory class
class MyClass: # the class you actually need
redFactory = Factory('red')
blueFactory = Factory('blue')
ex1 = redFactory.new('value1') # use the factory to return an instance
of MyClass initialized with the proper parameters
ex2 = blueFactory.new('value1')
Is that want you want to do ? If so, I may elaborate a little more...
More information about the Python-list