0
class phone:
    def __init__(self,brand,model,price,amount):
        self.brand=brand
        self.model=model
        self.price=price
        self.amount=amount

    


Nokia = phone("Nokia", 321, 150, 20)
Samsung = phone("Samsung", "A8", 190, 30)
iPhone = phone("iPhone", 5, 230, 40)

phones = []

def objectlist(Nokia,Samsung,iPhone):

    phones.append(Nokia)
    phones.append(Samsung)
    phones.append(iPhone)

objectlist(Nokia,Samsung,iPhone)

This is the problem that I'm working on for a school assignment, I was wondering if there is a way to add all objects associated with a class to a list, without having to point out each individual object and add it one by one?

daca171
  • 11
  • 1
  • 2
    if you don't need them as separate variables, then create them already in the list: `phones = [phone("Nokia", 321, 150, 20), phone("Samsung", "A8", 190, 30), phone("iPhone", 5, 230, 40)]` – h4z3 Dec 17 '21 at 11:15
  • 1
    within the constructor / initialized you can add `self` to some external list of instances. That way each objects adds itself to some list and you can keep track of all instances. Whether or not that is pretty or why you need that in the first place is a different question. – luk2302 Dec 17 '21 at 11:16
  • 2
    `class phone` defines a type of thing. That thing should only worry about itself. It should not be its job to keep track of things other than just itself. Organising a bunch of things is the job of code external to `class phone`. If you do instantiate `phone` a couple of times, and you want to keep those instances in a list… well… then do just that: instantiate them as objects in a list, not as separate variables. – deceze Dec 17 '21 at 11:20
  • Does this answer your question? [How to get all objects in a module in python?](https://stackoverflow.com/questions/5527415/how-to-get-all-objects-in-a-module-in-python) – Colonder Dec 17 '21 at 11:22

1 Answers1

0

Actually, there is a way.

But I have to change your wording a bit. Let's find all variables accessible from the current scope, which are instances of the given class, and collect them all into a list. A solution:

class Phone:
    def __init__(self, brand, model, price, amount):
        self.brand = brand
        self.model = model
        self.price = price
        self.amount = amount


nokia = Phone("Nokia", 321, 150, 20)
samsung = Phone("Samsung", "A8", 190, 30)
iPhone = Phone("iPhone", 5, 230, 40)

phones = []

all_variables = dict(globals(), **locals())

for name, var in all_variables.items():
    if isinstance(var, Phone):
        phones.append(var)

print(phones)

Returns:

[<__main__.Phone object at 0x1032a9cf8>, <__main__.Phone object at 0x1032a9d68>, <__main__.Phone object at 0x1032a9da0>]

Appreciations for the idea to Alex Martelli with this nice answer.

Yevgeniy Kosmak
  • 3,561
  • 2
  • 10
  • 26