简体   繁体   中英

Python3 OOP: Select all objects of a particular class w/o variables

I have simple class:

class ChannelMessages:
    def __init__(self, channel, date, message):
        self.channel = channel
        self.date = date
        self.message = message

... somecode here ...

for message in messages:
    ChannelMessages(name, message.to_dict()['date'], message.to_dict()['message']) 


... name, date, message - is a variables ...

I want now to select all ChannelMessages class objects and put it in a variable. Im dont need to saving it anywhere, i need to render this Classes once on my app.

Im trying to use something like Django ORM:

ChannelMessages.objects.all()

but i cant select them this way. So is there a way to select all created objects w\\o vars? Or i always shold specify variables for every created class object?

There's no built-in way to refer to all created instances of a particular class. APIs which enable you to do this have to implement this behaviour. Luckily you can very simply reproduce this behaviour with a class variable:

class ChannelMessages:
    all_messages = []

    def __init__(self, channel, date, message):
        self.channel = channel
        self.date = date
        self.message = message
        all_messages.append(self)

The all_messages list now hold a reference to all instantiated objects of its class, which, like all class variables, you can access either through the class itself ( ChannelMessage.all_messages ) or through any particular instance of the class ( self.all_messages ).

A more elegant solution would be using metaclasses and implementing __iter__ for the class itself, so you could write for message in ChannelMessages , but from a practical standpoint this works just as fine.

Why not store the items in a list?

allMessages = []
for message in messages:
    allMessages.append(ChannelMessages(name, message.to_dict()['date'], message.to_dict()['message'])

Which can also be done in a single line using a list comprehension:

allMessages = [ChannelMessages(name, message.to_dict()['date'], message.to_dict()['message']) for message in messages]

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