Why is main at the beginning of the output?
I just started learning classes in Python and ran into this problem(or not) that when the result is output, the first line is:
<__main__.Restaurant object at 0x0042DE90>
I began to be interested in this, but I did not find an answer on the Internet, so I hope that experts will help. Here is the entire code to clarify the issue:
class Restaurant:
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print(self.restaurant_name)
print(self.cuisine_type)
def open_restaurant(self):
print(self.restaurant_name+' is open!')
my_rest = Restaurant('Clot monet', 'classical')
print(my_rest)
my_rest.describe_restaurant()
my_rest.open_restaurant()
OUTPUT:
<__main__.Restaurant object at 0x0042DE90>
Clot monet
classical
Clot monet is open!
Process finished with exit code 0
1
Author: Arsen_Aganesov, 2019-01-25
1 answers
This is the standard repr representation of an object, inherited from object.
How to fix it-you can add your own repr description of the class instead of the standard one:
class Restaurant:
def __init__(self, restaurant_name, cuisine_type):
self.restaurant_name = restaurant_name
self.cuisine_type = cuisine_type
def describe_restaurant(self):
print(self.restaurant_name)
print(self.cuisine_type)
def open_restaurant(self):
print(self.restaurant_name+' is open!')
def __repr__(self):
return '{}(restaurant_name={!r}, cuisine_type={!r})'.format(self.__class__.__name__, self.restaurant_name, self.cuisine_type)
my_rest = Restaurant('Clot monet', 'classical')
print(my_rest)
my_rest.describe_restaurant()
my_rest.open_restaurant()
Output:
Restaurant(restaurant_name='Clot monet', cuisine_type='classical')
Clot monet
classical
Clot monet is open!
0
Author: insolor, 2019-03-13 18:29:11