Home > Back-end >  Create a list of Triangle objects
Create a list of Triangle objects

Time:12-01

I'm very new to Python and have an issue. I was wondering if there was a way I could create a list of objects created. For example, say I have a class:

list_triangles = []

def class Triangle:
    def __init__(self, h, w):
    self.h = h
    self.w = w

a = Triangle(5,6)
b = Triangle(3,3)

What I would have to add such that each time I defined a new object, it would append to list_triangles, such that in the end I have a list of objects?

e.g list_triangles = (a, b)

I'm thinking I'd have to make a for loop, but I'm not sure because what would I say for i in range ____?

CodePudding user response:

Put the arguments in a list, then iterate over that.

params = [(5, 6), (3, 3)]
list_triangles = [Triangle(*p) for p in params]

CodePudding user response:

If I understand you correctly, you want to have globaly accessible list of every created object, if so you can declare class variable and then append self to it in constructor to keep track of objects like so

class Cat():
    instances = []
    def __init__(self, name):
        self.name = name
        Cat.instances.append(self)

a = Cat("Bob")
b = Cat("John")

print(Cat.instances)
print(Cat.instances[0].name)

Which results in

>> [<__main__.Cat object at 0x00000000014BE790>, <__main__.Cat object at 0x00000000014BE610>]
>> Bob
  • Related