call an instance of a class in the interactive - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: call an instance of a class in the interactive (/thread-12401.html) |
call an instance of a class in the interactive - nzcan - Aug-23-2018 hello, I have created a class 'User': class User: def __init__(self, name, gender, age): self.name = name self.gender = gender self.age = age def __call__(self, name, gender, age): print(name) print(gender) print(age) user1 = User('dany wasser', 'gender: male', 21)I put this class in a file called saty.py then I imported the file 'saty.py' in the interactive mode of the interpreter by: import saty the file was successfully imported. now I want to call the single instance of this class 'user1' with all its attributes into the interactive mode of the interpreter. how can I do this? >>> print ... ? thanks in advance RE: call an instance of a class in the interactive - Gribouillis - Aug-23-2018 If you only want to call the instance, you simply do >>> user1()However, being callable is an uncommon feature for a class representing a user. In this case one would more traditionally define a conversion to string with a __str__() method.class User: def __init__(self, name, gender, age): self.name = name self.gender = gender self.age = age def __str__(self): return "User({!r}, {!r}, {!r})".format( self.name, self.gender, self.age) user1 = User('dany wasser', 'gender: male', 21)Then you could simply do >>> print(user1)The method could also be named __repr__() in this case in order to be called if some code asks for repr(user1) .
RE: call an instance of a class in the interactive - buran - Aug-23-2018 you will usei saty.user1 to reference name user1 from saty.py after this import.Now there are other problems with your class. For example you don't need this __call__ function. For this class it doesn't make sense it to be callable. If you want to create nice printable representation of the class, you will use __str__ . There is also another special method - __repr__ which you may want to implementit's bit different.class User: def __init__(self, name, gender, age): self.name = name self.gender = gender self.age = age def __str__(self): return 'User {}, gender: {}, age: {}'.format(self.name, self.gender, self.age) def __repr__(self): return 'User object: (id: {}, name: {}, gender: {}, age: {})'.format(id(self), self.name, self.gender, self.age) user1 = User('dany wasser', 'gender: male', 21)
RE: call an instance of a class in the interactive - nzcan - Aug-23-2018 (Aug-23-2018, 06:37 AM)Gribouillis Wrote: If you only want to call the instance, you simply do it works excellent! thanks a lot! (Aug-23-2018, 06:37 AM)buran Wrote: you will usei very sophisticated version! thanks a lot! |