简体   繁体   中英

how to perform mathematical operations over a two-level class object heirarchy

I have set up a two-level class object hierarchy - I'm not sure if I am doing this in the most efficient way, or even if I am using the correct terminology (unlikely), but here is a reproducible example:

import numpy as np

class mem:
    """this is a member with characteristics"""
    def __init__(self,i):
        self.val=i*i

class ens:
    """this is the ensemble"""
    def __init__(self,n):
        self.mem=[]
        for i in range(n):
            self.mem.append(mem(i))

num=10
e=ens(num)

print(e.mem[4].val)

gives the answer 16 as expected.

My question is how can I perform mathematical operations such as the max or mean across the ensemble member values?

I was hoping I could do something like this:

np.mean(e.mem[:].val)

but this gives the error

AttributeError: 'list' object has no attribute 'val'

The only way I could get to work was to copy the values into a list and then perform the average, but this seems not very pythony... I am sure there is a neater solution.

l=[]
for i in range(num):
    l.append(e.mem[i].val)
np.mean(l)

this works and gives: 28.5

For more "pythony" way you can use iterators, that way you can avoid creating duplicate lists:

num=10
e=ens(num)

from statistics import mean

print(mean(i.val for i in e.mem))

print(max(i.val for i in e.mem))

Prints:

28.5
81

You can add method or property in class env to get val from all elements in mem

class ens:

    @property
    def val(self):
        return [x.val for x in self.mem]

and then you can use e.val

print(np.mean(e.val))

import numpy as np

class mem:
    """this is a member with characteristics"""
    def __init__(self,i):
        self.val=i*i

class ens:
    """this is the ensemble"""
    def __init__(self, n):
        self.mem = []
        for i in range(n):
            self.mem.append(mem(i))

    @property
    def val(self):
        return [x.val for x in self.mem]

num = 10
e = ens(num)

print(e.mem[4].val)

print(np.mean(e.val))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM