Python learner -- trouble creating a class [closed] - python

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.

Related

Python - init argument not used in self [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 months ago.
Improve this question
I came by a code and wanted to get more understanding on when to use such arrangement.
What would be a good scenario of not using __init__'s argument (name) in self?
class ArgumentNotUsedInSelf:
def __init__(self, name: str):
self.type = "user"
user_one = ArgumentNotUsedInSelf("Mike")
print(user_one.type)
Any explanations from architectural (and not only) point of view are most welcome!
Some of the reasons for this can be:
Historical. The class used to use the argument, but it was changed so it's no longer meaningful. The argument was kept for backward compatibility.
Class hierarchy. This may be a child class of a class that uses the argument, but the child overrides the need for it. The argument is required for compatibility with the parent.
Sort of Barmar's historical example... let's say:
ArgumentNotUsedInSelf used to do something with name, but now doesn't.
But name is still used in SubClass, and changing everything could mess up dependent programs.
class ArgumentNotUsedInSelf:
def __init__(self, name: str):
self.type = "user"
class SubClass(ArgumentNotUsedInSelf):
def __init__(self, name):
super(SubClass, self).__init__(name)
self.name = name
x = SubClass('Mike')
print(x.name, x.type)
Output:
Mike user
This would be helpful if you want to store the field "name" of the created object and re-use it later:
class ArgumentNotUsedInSelf:
def __init__(self, name: str):
self.type = "user"
self.name = name
user_one = ArgumentNotUsedInSelf("Mike")
print(user_one.type)
print(user_one.name)

Class not running - getting no results [closed]

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()

TypeError when adding variable [closed]

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
I took working example code and tried to add another variable self.species = martian under the init method. Seems you cannot do this which doesn't make sense to me.
# A Sample class with init method
class Person:
# init method or constructor
def __init__(self, name, species):
self.name = name
self.species = martian
# Sample Method
def say_hi(self, name, species):
print('Hello, my name is', self.name)
print('I am', self.species)
p = Person('Martin')
p.say_hi()
TypeError: __init__() missing 1 required positional argument: 'species'
When creating the person p you need to pass the species parameter. As well, you are not using that argument in your function.
Calling could look like this:
p = Person("Martin", "martian")
Then within the constructor you reference the argument like this:
self.species = species
this is how your code should look like.
# A Sample class with init method
class Person:
# init method or constructor
def __init__(self, name, species):
self.name = name
self.species = species
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
print('I am', self.species)
p = Person('Martin', 'martian')
p.say_hi()
I suggest you watch some other beginner's video lectures on 'init' method and 'Object oriented programming in python' before writing these type of codes otherwise it would be very hard to understand beyond this point

Variable scope in __init__ method? [closed]

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

python error NameError name is not defined [closed]

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.

Categories

Resources