Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am new to python classes and I am trying to run this code but I don't get any results:
class Restaurant:
def __init__(self, mascalzone, it_fusion):
self.mascalzone = mascalzone
self.it_fusion = it_fusion
def describe_restaurant(self):
print(f"this restaurant is Italian and is named: {self.mascalzone}")
def open_restaurant(self):
print(f"the restaurant {self.it_fusion} is open , please come in!")
# make instance below:
restaurant = Restaurant('open', 9)
# printing two attributes individually:
print(f"this:{restaurant.it_fusion}")
print(f"that:{restaurant.mascalzone}")
# calling both methods:
restaurant.describe_restaurant()
restaurant.open_restaurant()
That is not how classes work. Your first part of code should be describing the class, and then the second be actually creating an instance of the class. So either you thought that you had to define classes inside of the definition, or you forgot to indent well.
in open_restaurant(), remove creating an instance of Restaurant and place it outside of the class definition. Then put the code calling both methods also outside of the code. The rest of your code is fine.
The code:
class Restaurant:
def __init__(self, mascalzone, it_fusion):
self.mascalzone = mascalzone
self.it_fusion = it_fusion
def describe_restaurant(self):
print(f"this restaurant is Italian and is named: {self.mascalzone}")
def open_restaurant(self):
print(f"the restaurant {self.it_fusion} is open , please come in!")
restaurant = Restaurant('open', 9)
restaurant.open_restaurant()
restaurant.describe_restaurant()
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last year.
Improve this question
I cannot figure out why this simple Python code to create a class called Resto will not run. The traceback says the name "Resto" is not defined (at the end of the code where I am making an instance of the class). But I successfully created other classes by following this exact format.
class Resto:
""" a model of a restaurant """
def __init__(self, name, cuisine):
""" attributes of the restaurant """
self.name = name
self.cuisine = cuisine
def describe_resto(self):
print (f"{self.name} features {self.cuisine} cooking.")
def resto_open(self):
print (f"{self.name} is open Tuesday through Sunday, from 6 to midnight.")
Alices = Resto ("Alice's", "Canadian")
Alices.describe_resto()
Alices.resto_open()
I think it is because Alices = Resto (...) line and the lines after that line is indented on the same level as the stuff inside Resto.
Try removing their indentation (make them align to the left with no spaces).
You must instantiate the class outside of the class itself, because at the time of execution, the class doesn't yet exist. It is trying to execute the lines to create an instance of the class, inside of the uninstantiated class itself. So un-indent the last 3 lines:
class Resto:
""" a model of a restaurant """
def __init__(self, name, cuisine):
""" attributes of the restaurant """
self.name = name
self.cuisine = cuisine
def describe_resto(self):
print (f"{self.name} features {self.cuisine} cooking.")
def resto_open(self):
print (f"{self.name} is open Tuesday through Sunday, from 6 to midnight.")
Alices = Resto ("Alice's", "Canadian")
Alices.describe_resto()
Alices.resto_open()
Output:
Alice's features Canadian cooking.
Alice's is open Tuesday through Sunday, from 6 to midnight.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am trying to find a way to store class attribute information in a list when the object is created. I am just learning python classes and am having some difficulty figuring out how to implement the str method correctly.
muffins = []
class Muffin:
def __init__(self,name,calories):
self.name = name
self.calories = calories
muffins.append(Muffin)
def __str__(self):
return self.name
banana_chocolate_chip = Muffin('banana_chocolate_chip', 250)
blueberry = Muffin('blueberry', 200)
pumpkin_pecan = Muffin('pumpkin_pecan', 225)
for muffin in muffins:
print(muffin)
When I run this code I get:
<class '__main__.Muffin'>
<class '__main__.Muffin'>
<class '__main__.Muffin'>
My desired output is:
banana_chocolate_chip
blueberry
pumpkin_pecan
Thanks in advance! :)
Use muffins.append(self) instead of muffins.append(Muffin) to get your desired output. muffins.append(Muffin) doesn't append an actual instance of the muffin class, passing self will refer to the instance that just got created.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
class Person():
def insert(self,name,age,idName):
self.name=name
self.age=age
self.idName=idName
def output(self):
print('name='+name+'\nage='+age+'\nidName='+idName)
j=Person()
j.insert('Alex','40','3143450603')
j.output
Nothing outputted in a terminal, maybe some syntax error
First of all in output method you have to access the variables with self..
Secondly, you are caaling output method without braces which needs to be fixed.
Try this :
class Person():
def insert(self,name,age,idName):
self.name=name
self.age=age
self.idName=idName
def output(self):
print('name='+self.name+'\nage='+self.age+'\nidName='+self.idName)
j=Person()
j.insert('Alex','40','3143450603')
j.output()
This is the output you will get :
name=Alex
age=40
idName=3143450603
In the method Person.output() you are referring to the local variables name, age and idName, whereas you should be referring to the object's members (self.name, ...), because the local variables do not exist at this point. They only existed in Person.insert().
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
class Person(object):
def __init__(self, age):
self.age = age
self.ageGroup = ageGroup
def findAgeGroup(self):
if age >= 80:
ageGroup= "old"
print ageGroup
John= Person(95)
John.findAgeGroup
So my Question is probably a pretty simple one. In the above code in the __init__ method the variable self.age is set when a new instance of the Person class is instantiated? And all of the other variables in the __init__ method are put there because they are related to self.age? For example in the findAgeGroup method age is used to derive a value for ageGroup. So would the only time you list self.ageGroup in the __init__ method be if you plan to derive the value from self.age which is called in when a new instance of the class is created?
In Python you actually always need the self to reference instance variables unlike e.g. Java's this:
def findAgeGroup(self):
if self.age >= 80:
self.ageGroup = "old"
print self.ageGroup
# also Python prefers snake_case: self.age_group
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
class Bird :
'''A base class to define bird properties.'''
count = 0
def_init_( self , chat )
self.sound = chat
Bird.count += 1
def talk( self ) :
return self.sound
NameError: name 'def_init_' is not defined
I tried using 2 underscores on both side of the 'init'
This looks like a simple typo. You're missing the space after def - it should be:
def __init__(self, chat):
you had lots of error in your script actually
1> indentation
2> give space after def
3> colon after def init( self , chat )
follow the rules then everything will be okay....
class Bird :
'''A base class to define bird properties.'''
count = 0
def __init__( self , chat ):
self.sound = chat
Bird.count += 1
def talk( self ):
return self.sound
You need to change your _init_ function to def __init__(self, chat):.
The __ is called a dunder, which is short for 'double underscore'. We usually use this, magic methods like instantiation. So for example, [] would be called __get__.
Whenever you see a dunder, you know it has a special use.