[BangPypers] problem with python classes

steve steve at lonetwin.net
Fri May 10 04:37:59 CEST 2013


Hi,


On Thursday 09 May 2013 09:11 PM, hiharry danny wrote:
> i have python 2.7.4......now suppose i have two new-style base classes ,
> i.e. class ClassName(object):
> and the two base classes are related by __init__ constructor where the
> __init__ constructor of one base class is accessed by the __init property
> of the other base class , for example :
>
> class ClassOne(object):
>          def __init__(self,value):
>                self.value = value
>
> class ClassTwo(object):
>           def __init__(self,inputvalues):
>                  self.values = []
>                   for i in inputvalues:
>                       self.values.append(ClassOne(inputvalues))
>
In this last statement, what's the point of iterating over inputvalues ? Do you 
really want to create as many instances of ClassOne as the number of inputvalues 
? Or was that for loop supposed to be something like:

...
for i in inputvalues:
     self.values.append( ClassOne(i) )
...

> if this be the case , then without using inheritance property of OOP ,i,e,
> without creating further new subclasses , how can I access other user
> defined methods of ClassOne class via Class Two class. The ouput value will
> be returned by a user defined method of ClassTwo but the computation will
> be done by a method of ClassOne which is called by the user defined method
> of class two ...?
>
> so what will be the solution ?

Umm, firstly there is nothing about the above code that is specific to new style 
classes. Perhaps it would be better if you explained what exactly you are trying 
to achieve with a real example (as in, a proper use case). Although it is 
possible to do what you are requesting by simply doing something like this:

 >>> class ClassOne:
...     def __init__(self,value):
...         self.value = value
...     def real_computation(self):
...         self.value += 1
...
 >>>
 >>> class ClassTwo:
...     def __init__(self, inputvalues):
...         self.values = []
...         for i in inputvalues:
...             # - assuming that you wanted to create a bunch of ClassOne
...             # instances based on inputvalues and populate self.values
...             self.values.append( ClassOne(i) )
...     def increment_all(self):
...         for i in self.values:
...             i.real_computation()
...
 >>> o = ClassTwo([10, 20, 30, 42])
 >>> [ i.value for i in o.values ]
[10, 20, 30, 42]
 >>> o.increment_all()
 >>> [ i.value for i in o.values ]
[11, 21, 31, 43]
 >>>

...it really doesn't make much sense to do something this way, given the limited 
information you have provided.

cheers,
- steve


More information about the BangPypers mailing list