K
K
K A2020-02-17 12:17:55
Python
K A, 2020-02-17 12:17:55

How to stack attributes of Python class objects?

There is a class based on it, there are several objects with the weight attribute, how to collect the attributes in a list, so that later you can sum up or highlight the largest or smallest value?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sswwssww, 2020-02-17
@russrage

class MyClass:
    instance_ref = []

    def __init__(self):
        MyClass.instance_ref.append(self)


a = MyClass()
b = MyClass()
c = MyClass()
d = MyClass()
a.weight = 3
b.weight = 4
c.weight = 5
d.weight = 6
add = sum([x.weight for x in MyClass.instance_ref])
print(add)
maximum = max([x.weight for x in MyClass.instance_ref])
print(maximum)

I
Ivan Melnikov, 2020-02-17
@immelnikoff

my_list = list()
my_list.append(obj1.weight)
my_list.append(obj2.weight)
print(max(my_list))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question