Simple questions on use of objects (probably faq)
bruno at modulix
onurb at xiludom.gro
Wed Mar 8 07:50:23 EST 2006
Brian Elmegaard wrote:
> Hi,
>
> I am struggling to understand how to really appreciate object
> orientation. I guess these are FAQ's but I have not been able to find
> the answers. Maybe my problem is that my style and understanding are
> influenced by matlab and fortran.
>
> I tried with the simple example below and ran into several questions:
> 1: Why can't I do:
> def __init__(self,self.x):
> and avoid the self.x=x
Before you assign a value to it, self.x does not exists.
> 2: Is it a good idea to insert instances in a list or is there a simpler
> way to do something with all instances of a given type?
Depends on your program. But there are at least ways to make this a bit
more transparent, see below.
> 3: Why canøt I say and get the maximum of instance attributes and a
> list of them?
> y_max=max(y[].x) and
y_max = max([s.x for s in y])
> ys=[y[].x]
ys = [s.x for s in y]
> 4: Can I avoid the dummy counter i in the for loop and do something
> like:
> yz=[y[:-1].x-y[1:].x]
based on the other snippet you posted:
> yz=[]
> for i in range(len(ys)-1):
> yz.append(ys[i+1]-ys[i])
yz = [next - current for next, current in zip(ys[1:], ys[0:-1])]
I'm not sure this is exactly what you want, but this should get you
started anyway.
Now how you could do it the OO way (Q&D, not really tested):
class Foo(object):
_instances = []
def __init__(self, x):
self.x = x # no, you won't avoid it
self._add_instance(self)
@classmethod
def _add_instance(cls, instance):
cls._instances.append(instance)
@classmethod
def get_instances(cls):
return cls._instances[:]
@classmethod
def get_values(cls):
return [i.x for i in cls.get_instances()]
@classmethod
def max(cls):
return max(cls.get_values())
@classmethod
def min(cls):
return min(cls.get_values())
@classmethod
def strange_computation(cls):
values = cls.get_values()
return [next - current \
for next, current in zip(values[1:], values[:-1])]
for value in [10.0, 110.0, 60.0]:
Foo(value)
Foo.get_values()
Foo.max()
Foo.min()
Foo.strange_computation()
HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"
More information about the Python-list
mailing list