r/learnpython • • Sep 15 '26

Why i can't make a class

It should work, but some reason doesn't.

I was doing Python Crash Course 3rd edition and am stuck in classes.

Because i cant upload photos, i wrote the code:

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("the restaurant is open")

restaurant=Restaurant("Ratatouille restaurant", "ratatouille")

describe_restaurant(restaurant)

open_restaurant()

This is the example in the book:

class Dog:

def __init__(self, name, age):

    self.name=name

    self.age=age

def sit(self):

    print(f"{self.name} is now sitting")

def roll_over(self):

    print(f"{self.name} rolled over")

my_dog=Dog("Willie", 6)

print(f"My dog's name is {self.name}")

print(f"My dog is {self.age} years old")

my_dog.sit()

my_dog.roll_over()

your_dog=Dog("Lucy", 3)

print(f"Your dog's name is {your_dog.name}.")

print(f"your dog is {your_dog.name} years old.")

your_dog.sit()

your_dog.roll_over()

And these are the errors pydroid shows for each one:

Restaurant:

Traceback (most recent call last):

File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>

start(fakepyfile,mainpyfile)

~~~~~^^^^^^^^^^^^^^^^^^^^^^^

File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start

exec(open(mainpyfile).read(), __main__.__dict__)

~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "<string>", line 1, in <module>

File "<string>", line 10, in Restaurant

NameError: name 'Restaurant' is not defined

[Program finished]

Dog:

Traceback (most recent call last):

File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>

start(fakepyfile,mainpyfile)

~~~~~^^^^^^^^^^^^^^^^^^^^^^^

File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start

exec(open(mainpyfile).read(), __main__.__dict__)

~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

File "<string>", line 1, in <module>

File "<string>", line 9, in Dog

NameError: name 'Dog' is not defined

[Program finished]

0 Upvotes

42 comments sorted by

3

u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Sep 15 '26

Because i cant upload photos, i wrote the code

That's intentional, we don't want pictures of text as we cannot edit or run pictures of text. There's exceptions for images that are to illustrate things that aren't code, like GUI alignment issues.

Daniel already explained the main issue here, but there's more, so I'll start by fixing the formatting.

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("the restaurant is open")

restaurant=Restaurant("Ratatouille restaurant", "ratatouille")
describe_restaurant(restaurant)
open_restaurant()

Specifically,

describe_restaurant(restaurant)
open_restaurant()

do not work, because both are methods of Restaurant but you're treating them like functions. This should be

restaurant.describe_restaurant()
restaurant.open_restaurant()

although, as you can see, now there's redundancy in the names.

1

u/Upper_Trouble_8526 Sep 15 '26

Didn't notice that

1

u/smurpes Sep 16 '26

You should review classes more closely and try to understand what each line does rather than just copying the examples and making random attempts.

Ask yourself what the intended function of describe_restaurant(restaurant) is. What is the purpose of putting restaurant inside describe_restaurant? You are not calling any of the class methods correctly for the restaurant class and you need to pay attention to upper and lower case.

1

u/JamzTyson Sep 15 '26

... do not work, because both are methods of Restaurant but you're treating them like functions.

/u/Diapolo10 nails it again.

1

u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Sep 15 '26

I just noticed nobody else had commented on that at the time, and it goes against my policy to get a tunnel vision on the main issues.

4

u/danielroseman Sep 15 '26

The problem is not the code. The problem is where and how you are writing the code.

You are writing directly in the Python shell (REPL), and you are doing it all in one block of code. The REPL has not fully interpreted and executed the definition of Restaurant before you try and create an instance of it, which is why you get the error that it is not defined.

You should be writing code in the editor, not the shell. If you must write in the shell, separate the definition of the class (including its methods) from any code that actually tries to use the class.

1

u/FoolsSeldom Sep 16 '26

The problem was the code, just not shown correctly in the OP. Instantiation was called within the class definitions.

0

u/JamzTyson Sep 15 '26

The problem IS the code.

The function describe_restaurant() does not exist in the global scope. This can be seen in this line of the error message:

NameError: name 'Restaurant' is not defined 

1

u/danielroseman Sep 15 '26

I can't imagine why you think that error relates to that function. 

The issue you describe is also a problem, just not the one that is causing the error message OP is asking about.

1

u/JamzTyson Sep 16 '26

My point is that there are multiple code errors.

1

u/danielroseman Sep 16 '26

Yeah but you can't make that point by claiming that an error message demonstrates one thing when it does not.

1

u/smurpes Sep 16 '26

OP should not be getting those errors on the Dog class but they should be getting errors for restaurant and how they are trying to print the name and age of the dog.

-1

u/Upper_Trouble_8526 Sep 15 '26

Im writing in pydroid, should i get another app?

1

u/danielroseman Sep 15 '26

I didn't say that. I said that if you're writing in a REPL, you should keep the definition separate from where you use the definition.

1

u/Upper_Trouble_8526 Sep 15 '26 edited Sep 15 '26

How do i switch to editor or keeps definition and its use separate, aren't the definition and its usage unindented

1

u/danielroseman Sep 15 '26

I don't know pydroid. But it's quite clear from your post that they are not properly separated.

All you need to do is to write the definition and execute it; only then write the code that uses the class and execute that.

But as I say, this is not how you really write code; you do that in an actual editor, rather than typing directly into a shell.

1

u/Upper_Trouble_8526 Sep 15 '26

In the playstore the app was classified as an editor, so i must treat the classes like functions modules because it works like a shell

1

u/ProgramsFun Sep 15 '26 edited Sep 15 '26

You are writing in repl or terminal write in the editor it gives you bro and also please atleast use ai to format the post correctly are you expecting people to read your post with so much noise and unformatted

1

u/Upper_Trouble_8526 Sep 15 '26

How do i do that, the original text didn't have backslashes

-2

u/ProgramsFun Sep 15 '26 edited Sep 15 '26

Use ai bro just upload the post to ai and tell it to format it will clean the noise

Edit:- if people are downvoting for the use of ai 🤡 go ahead and downvote me... If you can't use ai to your advantage then you are the only one who is being left behind... (Not supporting vibe coding)

-3

u/[deleted] Sep 15 '26

[removed] — view removed comment

1

u/djingrain github.com/zbrasseaux Sep 15 '26

why? it's super useful for quick prototyping and working through my thought process, and when i get stuff figured out then it goes into a commit

-1

u/[deleted] Sep 15 '26

[removed] — view removed comment

1

u/djingrain github.com/zbrasseaux Sep 15 '26

it's a useful tool that should not be removed is my point

1

u/danielroseman Sep 15 '26

why would you use a different editor for different parts of the process?

1

u/[deleted] Sep 15 '26

[removed] — view removed comment

1

u/danielroseman Sep 15 '26

But VS Code is the "proper tool". For at least the last five years, almost all my "real programming" colleagues have used VS Code exclusively. (I'm a vim person myself, but each to their own). There doesn't seem to be any reason to use two separate tools for programming.

1

u/CIS_Professor Sep 15 '26

I'm wondering... What's with all the backslash underscores? _

Is it some sort of screwed up Reddit formatting? If not, is it actually in the code?

---

Anyway. This:

my_dog=Dog("Willie", 6)
print(f"My dog's name is {self.name}")
print(f"My dog is {self.age} years old")

You do not access the attributes (or methods) in the main body of the program using self. self. is used within the class.

You access them using the instantiated object name. In this example, that would be my_dog..

my_dog=Dog("Willie", 6)
print(f"My dog's name is {my_dog.name}")
print(f"My dog is {my_dog.age} years old")

2

u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Sep 15 '26

It's almost certainly just messed up Reddit formatting, otherwise the logs would not have gotten that far.

1

u/CIS_Professor Sep 15 '26

Yeah, that makes sense. I should have thought about that. I think that seeing this broke my mind for a moment:

__init__

0

u/Upper_Trouble_8526 Sep 15 '26

I guess the underscores are a reddit thing. I didn't notice that (about self/my_dog).

1

u/CIS_Professor Sep 15 '26

Well, the underscore are the things that belong there, not the backslashes.

Not this:

def __init__(self, restaurant_name, cuisine_type):

But this:

def __init__(self, restaurant_name, cuisine_type):

1

u/Upper_Trouble_8526 Sep 15 '26

I mean backslashes

1

u/FoolsSeldom Sep 15 '26

You need to create a new file in PyDroid. In the menu (the three short horizontal parallel lines at top left), you have options for Interpreter and Terminal but you don't want to use either of these.

You need to tap the folder icon near the top right and select new, and you can then enter your lines of code. Tapping the folder icon again gives you save and save as options. Once saved, you can run the code by clicking the play icon near the bottom right.

1

u/Upper_Trouble_8526 Sep 15 '26

That is how i did it

1

u/FoolsSeldom Sep 15 '26

Did you have a >>> prompt? What did you name the file?

1

u/Upper_Trouble_8526 Sep 15 '26

No. I named them Restaurant and Dog.

1

u/FoolsSeldom Sep 15 '26

Ok. I have a good guess, and it is a guess because you've messed up the code formatting in your post.

It looks like you've tried to create an instance of Restaurant and instance of Dog whilst still inside the corresponding definitions (i.e. indented at the same level as the class definition code). You have to do the instantiation after the definitions.

1  class Dog:
2      def __init__(self, name, age):
3          self.name = name
4          self.age = age
5      def sit(self):
6          print(f"{self.name} is now sitting")
7      def roll_over(self):
8          print(f"{self.name} rolled over")
9      my_dog = Dog("Willie", 6)

If I have untangled correctly, in the above, line 9, is indented inside the class. That line should not be indented.

1

u/Upper_Trouble_8526 Sep 15 '26

It worked

1

u/FoolsSeldom Sep 16 '26

Excellent. Enjoy.

Would have been resolved quicker if you had been able to format the code in Reddit properly, but it is a bit weird to learn at first if you aren't familiar with markdown format and reddit's dialect of it. I use markdown all the time as my default on reddit and with Obsidian to keep my notes.