Reputation: 61
This is the code I'm working on. I created some users, giving them a name, surname and a value.
Is there a way to return and print all, for instance, name of every user I created?
class Bacheca:
def __init__(self, name, surname, value):
self.name = name
self.surname = surname
self.value = value
user1 = Bacheca("John", "Black", 1)
user2 = Bacheca("Mark", "Green", 2)
user3 = Bacheca("Phil", "White", 3)
What I would like it's to print, for example, all the name of each users:
John
Mark
Phil
Is it possibile?
Thank you for your time.
Upvotes: 2
Views: 100
Reputation: 7887
The other answer is creative solution that I may have a use for in the future but caution should be taken with it. As noted in the comments it will keep a reference to your class instances, thus the garbage collector won't delete them properly (i.e. none of the class instances will be deleted until the last instance is unused [even then it may act funky and not delete properly]). There are ways around this (such as weakref
or using the __del__
magic method) but if you are more of a novice I would probably avoid it. If all you want is a list then make a list:
users = []
users.append(Bacheca("John", "Black", 1))
users.append(Bacheca("Mark", "Green", 2))
users.append(Bacheca("Phil", "White", 3))
for user in users:
print(user.name)
# or
print([user.name for user in users])
Also if you aren't doing anything else with your class and you are just using it to group attributes together then you may want to use a namedtuple
.
from collections import namedtuple
Bacheca = namedtuple('Bacheca', 'name surname value')
# it acts the same as your class
users = []
users.append(Bacheca("John", "Black", 1))
users.append(Bacheca("Mark", "Green", 2))
users.append(Bacheca("Phil", "White", 3))
for user in users:
print(user.name)
Upvotes: 1
Reputation: 19885
If you want to do it in the object itself, use a class variable in conjunction with a static method:
class Bacheca:
created_users = []
def __init__(self, name, surname, value):
self.name = name
self.surname = surname
self.value = value
Bacheca.created_users.append(self)
@staticmethod
def created():
return Bacheca.created_users
user1 = Bacheca("John", "Black", 1)
user2 = Bacheca("Mark", "Green", 2)
user3 = Bacheca("Phil", "White", 3)
print([user.name for user in Bacheca.created()])
Output:
['John', 'Mark', 'Phil']
Every time __init__
is called (for initialisation of a new instance), the created object will be appended to created_users
, which is a variable of the class, as opposed to an instance. Therefore, it persistently holds a reference to every instance that has been created.
You could add more bells and whistles by, say, overriding __del__
, but that is probably beyond the scope of this question.
Upvotes: 2