0

I have sample class and instances:

class A:
   def __init__(self, num)

#instances
a = A(2)
b = A(4)
c = A(5)
d = A(7)

In another class (class B) within a method, I have to get the highest value among the arguments 2,4,5,7 because I need it for a conditional statement. But I'm having a hard time coding because the instances were put in a list. That is,

lst = [a,b,c,d]

So,

class B:
  def __init__(self, point_list)

  def com()
    x = 0
    while x < max(other_class.point_list.num)

lst = [a,b,c,d]
other_class = B(lst)

From def com(), I need 7 to be the max value I am comparing to x but I don't know how I can get it. My code was wrong. I don't even know if the max function is to be used.

The error that pops when I use the max function is:

'list' object has no attribute 'num'
chilliyayi
  • 19
  • 3

3 Answers3

0

you need to iterate over the list and get the maximum element

>>> 
>>> class B:
...     def __init__(self, point_list):
...             self.pl = point_list
...     def com(self):
...             return max(self.pl, key=lambda x:x.num).num
... 
>>> other_class = B(lst)
>>> other_class.com()
7
sahasrara62
  • 10,069
  • 3
  • 29
  • 44
0

You need to use the key argument of max(). Also, if you want to call other_class.com() to get the maximum value, then the function com() has to have a self argument:

class A:
   def __init__(self, num):
      self.num = num

#instances
a = A(2)
b = A(4)
c = A(5)
d = A(7)

class B:
  def __init__(self, point_list):
    self.point_list = point_list

  def com(self):
    x = 0
    while x < max(self.point_list, key=lambda n: n.num):
        # Code goes here

lst = [a,b,c,d]
other_class = B(lst)

The key=lambda n: n.num makes max() return the A instance with the highest .num. Also, __init__ is a function, so it needs a colon after it, and you need to assign self.num = num and self.point_list = point_list

Ukulele
  • 612
  • 2
  • 10
  • It's probably better to write `max_x = max(self.point_list, key=attrgetter('num')); x = 0; while x = max_x: ...` to avoid redoing the `max` calculation at every iteration of the loop. – Stef Feb 26 '23 at 15:52
  • Also note that `max([A(2), A(7)])` will return `A(7)`, ***not*** just `7`, so at least it should be `x < max(self.point_list).num`, not `x < max(self.point_list)`. Or you can do instead: `x < max(map(attrgetter('num'), self.point_list))` – Stef Feb 26 '23 at 15:55
-1

It is confusing what you want but from what I understand is you want to find max value of point_list. You can do the following:

class B:
  def __init__(self, point_list):
    self.point_list = point_list

  def com(self):
    x = 0
    while x < max(self.point_list):
        pass

lst = [a,b,c,d]
other_class = B(lst)
Sahil
  • 9
  • 1
  • 2