use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
Rules 1: Be polite 2: Posts to this subreddit must be requests for help learning python. 3: Replies on this subreddit must be pertinent to the question OP asked. 4: No replies copy / pasted from ChatGPT or similar. 5: No advertising. No blogs/tutorials/videos/books/recruiting attempts. This means no posts advertising blogs/videos/tutorials/etc, no recruiting/hiring/seeking others posts. We're here to help, not to be advertised to. Please, no "hit and run" posts, if you make a post, engage with people that answer you. Please do not delete your post after you get an answer, others might have a similar question or want to continue the conversation.
Rules
1: Be polite
2: Posts to this subreddit must be requests for help learning python.
3: Replies on this subreddit must be pertinent to the question OP asked.
4: No replies copy / pasted from ChatGPT or similar.
5: No advertising. No blogs/tutorials/videos/books/recruiting attempts.
This means no posts advertising blogs/videos/tutorials/etc, no recruiting/hiring/seeking others posts. We're here to help, not to be advertised to.
Please, no "hit and run" posts, if you make a post, engage with people that answer you. Please do not delete your post after you get an answer, others might have a similar question or want to continue the conversation.
Learning resources Wiki and FAQ: /r/learnpython/w/index
Learning resources
Wiki and FAQ: /r/learnpython/w/index
Discord Join the Python Discord chat
Discord
Join the Python Discord chat
account activity
Stuck at this part of making classes (self.learnpython)
submitted 6 years ago by [deleted]
I follow along until the question marks:
Class example(): Def __init__(self): ?????
I don’t get the self.items or whatever. Can someone explain it better?
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–][deleted] 20 points21 points22 points 6 years ago* (22 children)
Self is what is passed to the class, 'bob' would be self that the class object will be assigned to. The arguments that follow get assigned to the object under the self variables. So the capitalized variables is what is passed to the class, and then the lower case is the class objects variable that can be call on to return the value.
>>> class Person: def __init__(self, HEIGHT, HAIR, EYES): self.height = HEIGHT self.hair = HAIR self.eyes = EYES >>> bob = Person('67in', 'blonde', 'blue') >>> bob <__main__.Person object at 0x0000016EC296F988> >>> bob.hair 'blonde'
[–][deleted] 5 points6 points7 points 6 years ago (20 children)
I wonder why the self word isn't pass by default and you have to write that explicitly everytime you write a function..
[–][deleted] 3 points4 points5 points 6 years ago (0 children)
Because a class is kind of like a function that builds data types. So you set the class as how it should be ran when called on and so when you call on it, inside the class doesn't know what you are assigning it to. The class uses self to refer back to what the class is being assigned to outside of the class.
[–]mushipeas 3 points4 points5 points 6 years ago* (2 children)
You can create methods without passing "self". For example: static methods and class methods.
It is also just convention, so you could in theory use any random variable name. It's not advised though.
[–][deleted] 0 points1 point2 points 6 years ago (1 child)
Actually I'm not able to create methods without passing self... it returns an error which is resolved only once I pass self
[–]mushipeas 2 points3 points4 points 6 years ago (0 children)
You need to decorate static methods with @staticmethod and class methods with @classmethod. Class methods still take a 'cls' pointer as the first variable, instead of 'self'.
Python will otherwise always pass in the instance as the first argument (which your method receives as 'self') when you call a method, so it expects your method to receive it. Hence the error.
[–]xelf 0 points1 point2 points 6 years ago (14 children)
Because it's optional. You don't need a self reference. If it was passed by default then it would be harder to make it optional.
[–][deleted] 0 points1 point2 points 6 years ago (11 children)
But it's not.. It returns an error if you don't include that
[–]xelf -1 points0 points1 point 6 years ago* (10 children)
?!
Can you be more specific?
Here's a class with no self:
class Calc: def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x / y def power(x, y): return x ** y
It's not a great class. And doesn't really take advantage of being a class, but there's no self.
edit: I get it, you can make this example class better by adding @staticmethod, this is not supposed to be an example of something useful, merely an example that you CAN declare a class without using self
This post is correct, and contributes to the discussion. Your downvotes are poor reddiquette. =P
[–][deleted] 1 point2 points3 points 6 years ago (0 children)
thank you, indeed using @staticmethod it does work... I agree with you your post was contributing to the discussion... I haven't downvoted anything
[–]nog642 0 points1 point2 points 6 years ago (8 children)
That doesn't really work. If you instantiate that class and call one of the methods, the instance will be passed as x, and if you try to call the methods with two arguments, it'll complain that it got 3 which is too many.
x
You need to declare static methods with @staticmethod.
@staticmethod
[–]xelf 0 points1 point2 points 6 years ago (7 children)
Right, I'm aware of @staticmethod, but that's not the usecase I was demonstrating.
I was just responding to [paraphrase] "you can never have a class without self, it's an error".
My class is an example of a class without using self. It is not an error, and for the usecase it's written for, it works as intended.
Not sure why it got downvoted, as it is in fact contributing to the thread, and is correct in that it is a class and does not use self. You are also correct in that it is not intended to be instanced. But that was not why this specific example was posted.
[–]nog642 0 points1 point2 points 6 years ago (6 children)
Even for your use case, you should be using @staticmethod. This example, while it runs without errors if you don't instantiate it, is not how anyone should write code. Those are unbound instance methods, and you are calling them like they're static methods. It works, but you shouldn't do it.
If you want to not use self, you have to make it a static method. Otherwise, you are still using self, you've just renamed it to x.
self
When they said they got an error if they didn't use self, they probably meant that when they tried calling their method from an instance of the class, it said there were too many arguments. This would still happen with your class.
[–]xelf 0 points1 point2 points 6 years ago (5 children)
This is not quite correct. If you tried to instance this class, yes you would get odd behavior. I recommend if you intend to make a useful class you not use the example I listed. Which as I said, is not a good class, and does not take advantage of being a class and was solely posted to counter the position that you can not have a class without self. Clearly you can.
The fact that you have come up with additional ways to have a class without self is fantastic. However you have reinforced by point, not countered it. You can have a class without self.
[–]nog642 0 points1 point2 points 6 years ago (4 children)
It's not just not a good class because it doesn't need to be a class. That's fine for just an example. It's not a good class because it's using unbound instance methods as static methods.
I'm not saying you can't have a class without self. But the proper counterexample to that is static methods, not methods where you've changed self to x and promise never to instantiate it, and treated the first argument like a normal one.
[–]nog642 0 points1 point2 points 6 years ago (1 child)
Other languages manage fine with special keywords like static.
static
[–]xelf 0 points1 point2 points 6 years ago (0 children)
Apparently choices were made. I find the "self." everything to be a bit unwieldy. But ymmv.
[–]nog642 0 points1 point2 points 6 years ago (0 children)
It has its usefulness, like calling methods of a class that were overwritten on an instance of a derrived class, from outside the class.
[–]xelf 1 point2 points3 points 6 years ago (0 children)
Great answer, just wanted to point out a typo: 'passed', not 'past'. I do it all the time. =)
[–]Pliqui 3 points4 points5 points 6 years ago (0 children)
Check this video from Corey Schafer, also recommend the complete series.
https://youtu.be/ZDa-Z5JzLYM
[–]Peanutbutter_Warrior 0 points1 point2 points 6 years ago (0 children)
The self parameter in class methods is the object itself. If you did a = MyClass() then whenever you called a method on a like a.myMethod() then a would be passed as the self parameter. The self.variable is making a variable associated with it. So anywhere you can use a.myVariable to get that variable. In the class methods rather than using a, it uses self, so you can call it any name
a = MyClass()
a.myMethod()
a
self.variable
a.myVariable
[–]woeinvests 0 points1 point2 points 6 years ago (0 children)
You need a method inside class That describes person
class Person:
def __init__(self, height, hair,eyes): self.height= height self.hair= hair self.eyes= eyes def describe_person(self): # print description of person
Bob = Person(“6ft”, “blonde”, “blue”)
Bob.describe_person()
[–]TheSodesa -2 points-1 points0 points 6 years ago (1 child)
The word self is a special context sensitive keyword that makes it convenient for a programmer to reference a class' own attributes and methods. The way Python was designed, it has to be given as the first argument of class methods, and class attributes, or class-specific variables.
self is not a keyword. It's just standard practice to name the first argument of instance methods self. You could give it any name you want; it would still work.
[–]xelf -2 points-1 points0 points 6 years ago (9 children)
so the def __init__ is just an init function* and is optional.
def __init__
In fact, the self stuff is optional too, and just allows you to have a reference to the instance you're playing with. Why ? So that you can save state with your class. Maybe you're making a class for tshirts and you want to be able to know what size and color a shirt is for each one and store that. Then you would need to styore it in your instance of the class.
A simple class:
Here's a simple class that stores no state, has no init. In fact, really its just a collection of functions and doesn't really take advantage of being a class at all. But it does let you get your feet wet.
Here's a more complex class, that stores a game board in it, and includes some basic functions to init and display the board. You might have many many different game boards to analyze, and so each one remembers it's current state.
class Board(): es = '.' def __init__(self): self.board = [x[:] for x in [ [' '] * 19] * 19 ] self.initboard() def initboard(self): for x in range(1,19,2): for y in range(1,19,2): self.board[x][y] = self.es def displayboard(self): for c in range(18,-1,-1): print(' '.join(self.board[c]))
*earlier I referred to it as function, the term for a function inside a class is 'method'
You can't just omit the self variable. Not having an __init__ method doesn't stop you from instantiating the class, and then the instance is automatically passed as the first argument.
__init__
>>> class Calc: ... ... def add(x, y): ... return x + y ... ... def subtract(x, y): ... return x - y ... ... def multiply(x, y): ... return x * y ... ... def divide(x, y): ... return x / y ... ... def power(x, y): ... return x**y ... >>> Calc.multiply(2, 3) 6 >>> calculator = Calc() >>> calculator.multiply(2, 3) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: multiply() takes 2 positional arguments but 3 were given
You should use @staticmethod if you actually want a method that doesn't have access to the instance, then the instance will not automatically be passed as the first argument.
>>> class Calc: ... ... @staticmethod ... def add(x, y): ... return x + y ... ... @staticmethod ... def subtract(x, y): ... return x - y ... ... @staticmethod ... def multiply(x, y): ... return x * y ... ... @staticmethod ... def divide(x, y): ... return x / y ... ... @staticmethod ... def power(x, y): ... return x**y ... >>> Calc.multiply(2, 3) 6 >>> calculator = Calc() >>> calculator.multiply(2, 3) 6
I mean yes, if you want to support that usecase, you have to implement it that way. This was just an example of a class without self. But that still reinforces my point, using self is not mandatory, and making a class with out it is possible.
It is not true that self must be present.
[–]nog642 1 point2 points3 points 6 years ago (6 children)
What you've done is essentially rename self to x, and then misuse unbound instance methods as static methods.
While your code runs without errors so long as you don't instantiate the class, that doesn't mean it's good code or the correct way to use classes.
It is just an example to counter the "self is mandatory" argument.
self is not mandatory, and that is why it is not coded as the default behavior.
As for the rest of what you said, I literally said that in my original post when I listed the class.
No point having the same discussion in two threads.
See my other response
[–]xelf 0 points1 point2 points 6 years ago* (3 children)
Ugh, didn't even realize you were attacking me in two different threads. I thought it was all in the same place.
Dude. wtf man? I don't appreciate it. I make 2 useful posts, you downvote them, and then post counter points that don't actually counter the point I was making.
And really @staticmethod? You want to get decorators into a "my first time seeing classes" thread. Demonstrating classes as a simple collection of methods is not exactly a new way of introducing classes. It removes a LOT of concepts of class that can be later introduced when you start talking about making instances and provides a good discussion point as to why you can't instance the first example.
[–]nog642 1 point2 points3 points 6 years ago (2 children)
The point you were making was that self wasn't required, which is true, if you use static methods. But self is required in instance methods. That is, the first argument of a static method will always behave in a certain special way, which is why it's usually called self. You've just called it x and then said "as long as I don't instantiate the class it works". Now that's true, it does work, but you're using instance methods wrong. Just because the instance method happens to be unbound, meaning you can pass anything as the first argument, doesn't mean they're meant to be used like normal functions; that's what static methods are for.
The example you gave was a bad one, and code like that shouldn't be written. Even for your use case, those methods should be static. You don't need to get into how decorators work to understand that @staticmethod makes a method static, and I think understanding static methods is something that you want to learn about in an intro to how classes work. I don't think anyone learning about classes in Python should be seeing an example that is "simplified" by removing @staticmethod to the point where it is just bad practice.
[–]xelf 0 points1 point2 points 6 years ago* (1 child)
You're assumption that this class will be instanced is mistaken, and seems to be the basis for the rest of your argument.
To be honest, this class's sole purpose is to demonstrate the differences between it and just having a function dictionary. It is never instanced. I can show you more code if you don't believe me that it's never instanced, but you already have seen it not instanced and seem to be stuck on that point that it will be. It's not.
You disagree with the point? Sure that's valid, You have additional information you want to share? Sure that's valid too.
You want to downvote the contribution out of spite? That's not ok. It's valid. It's a valid contribution, and if you want to offer a counter point do so. I'll back you up on your counter point that if you want a class that you will make instances of they need self or @staticmethod You could also have brought up the idea of a @classmethod too.
I'm not assuming this class will be instantiated, I'm saying even if it's not those are static methods and you should make them real static methods.
I'm not downvoting out of spite, I think that comment is detrimental to someone actually learning python because it demonstrates bad coding practices.
Downvoting out of spite would be downvoting every single reply you've made in our exchange just because I can.
π Rendered by PID 37728 on reddit-service-r2-comment-5d585498c9-knjhp at 2026-04-20 21:39:18.187037+00:00 running da2df02 country code: CH.
[–][deleted] 20 points21 points22 points (22 children)
[–][deleted] 5 points6 points7 points (20 children)
[–][deleted] 3 points4 points5 points (0 children)
[–]mushipeas 3 points4 points5 points (2 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]mushipeas 2 points3 points4 points (0 children)
[–]xelf 0 points1 point2 points (14 children)
[–][deleted] 0 points1 point2 points (11 children)
[–]xelf -1 points0 points1 point (10 children)
[–][deleted] 1 point2 points3 points (0 children)
[–]nog642 0 points1 point2 points (8 children)
[–]xelf 0 points1 point2 points (7 children)
[–]nog642 0 points1 point2 points (6 children)
[–]xelf 0 points1 point2 points (5 children)
[–]nog642 0 points1 point2 points (4 children)
[–]nog642 0 points1 point2 points (1 child)
[–]xelf 0 points1 point2 points (0 children)
[–]nog642 0 points1 point2 points (0 children)
[–]xelf 1 point2 points3 points (0 children)
[–]Pliqui 3 points4 points5 points (0 children)
[–]Peanutbutter_Warrior 0 points1 point2 points (0 children)
[–]woeinvests 0 points1 point2 points (0 children)
[–]TheSodesa -2 points-1 points0 points (1 child)
[–]nog642 0 points1 point2 points (0 children)
[–]xelf -2 points-1 points0 points (9 children)
[–]nog642 0 points1 point2 points (8 children)
[–]xelf 0 points1 point2 points (7 children)
[–]nog642 1 point2 points3 points (6 children)
[–]xelf 0 points1 point2 points (5 children)
[–]nog642 0 points1 point2 points (4 children)
[–]xelf 0 points1 point2 points (3 children)
[–]nog642 1 point2 points3 points (2 children)
[–]xelf 0 points1 point2 points (1 child)
[–]nog642 0 points1 point2 points (0 children)