Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python

I have a question about variable in the class

class room: table = 1 table1 = table + 1 def eat(self,table1): print(table1)

after I proceed above code, the error shows: TypeError: eat() missing 1 required positional argument: 'table1' I have questions, why does the table1 couldn't directly pass into eat as a parameter like function, and If every time when I want to use the variable in the class, I need to add self before them. Because I feel add self. before every variable feel a little troublesome, lol hope you could explain to the reason for that.

2 Answers

Alex Koumparos
seal-mask
.a{fill-rule:evenodd;}techdegree
Alex Koumparos
Python Development Techdegree Student 36,862 Points

Hi Yi,

It's difficult to comment on your code because you didn't use Markdown to format it (if you don't know how to use Markdown, there is a link to the cheatsheet right below every question/answer/comment field). Or you could ask for help with Markdown. In the future, when you have code more than a line or two long, it is going to be impossible to help you without properly formatted code.

As for your questions, table1 can be passed into your method just like a function. Consider the following method:

def my_method(self, table):
    print(table)

my_method(table1)

and the following function:

def my_function(table):
    print(table)

my_function(table)

As you can see, passing the table into the function is just like passing it into the method. The only difference is in the declaration of the method, where you always need to make the first parameter of the declaration self. The reason for this is that Python wants you to be explicit about which object your are referencing in your method.

As for your frustration with needing to prefix object-level entities with self. Yes, it is troublesome, but there is a reason for it. If you are interested, you can read Guido van Rossum's (the creator of Python) own explanation for why. It does help to understand the reasoning.

Hope that helps

Alex

Thank u so much u explained so details, and I will read u give the link. Best wishes to u.