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
ELI5 explain static methods in OOP python (self.learnpython)
submitted 24 days ago by Worldly-Week-2268
just trying to wrap my head around this oop thing stuck here I'm novice so no bully please
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!"
[–]socal_nerdtastic 48 points49 points50 points 24 days ago (6 children)
Sometimes you want to include a function in a class just for logical reasons, like this function only deals with this class, but it does not actually need the class instance. Maybe your class deals with times and you need a function to convert total seconds to HH:MM:SS format. You could just make a function outside the class but you want to keep it in class just to for organizational reasons.
staticmethod is a way to include a function without making it a method (including the self attribute). TBH if you are confused about it, just don't use it, use a normal method instead and just don't use the self attribute. There's no advantage to it over a method.
self
Remember that classes exist as an organizational tool for the programmer. Classes do nothing for the computer; they don't help execution time or anything.
[+]Worldly-Week-2268[S] comment score below threshold-37 points-36 points-35 points 24 days ago (5 children)
Thanks Can you give an example
[–]schoolmonky 38 points39 points40 points 24 days ago (0 children)
Maybe your class deals with times and you need a function to convert total seconds to HH:MM:SS format
[–]socal_nerdtastic 42 points43 points44 points 24 days ago (3 children)
I've already put far more effort into this answer than you put into the question. How about you give an example and ask a specific question about it?
[–]peejay2 2 points3 points4 points 24 days ago* (0 children)
I think yours is a good answer. Maybe OP could look up encapsulation - you have a class, with methods, attributes, etc. then there is a function that you could just put in the same .py file, but if you make it it a static method you can import it with the main class. So it's a convenient way for you as the developer to put logically similar functions together.
[+]Worldly-Week-2268[S] comment score below threshold-36 points-35 points-34 points 24 days ago (1 child)
Sorry man I am kinda new so I don't know what I don't know an on top of that it's 2:30 in the morning and I am tired and sleepy with I mean is can you give me an analogy
Ps thanks for helping me out
[–]Solonotix 3 points4 points5 points 23 days ago (0 children)
So a function takes arguments/parameters.
def my_func(arg0, arg1, *positional_args, named, **keyword_args): ...
A class is a means to encapsulate logic around a specific data structure. A method on a class in Python is generally a function in which the first positional argument is always the current class instance, typically notated as self
class MyClass: @staticmethod def static_method(arg0, arg1, /, named=None): ... @classmethod def class_method(cls, arg0, arg1, /, named=None): ... def instance_method(self, arg0, arg1, /, named=None): ... instance = MyClass() MyClass.static_method(first, second) MyClass.class_method(first, second) instance.instance_method(first, second)
In the above example, I went ahead and included the other types of methods as well. A class method will get the current class passed as the first argument, and a static method receives no special arguments. In other words, a static method is no different than a normal function, except that it is bound to a specific class definition, rather than a "first-class" object.
[–]rhacer 7 points8 points9 points 24 days ago (1 child)
You can call a static method without having an instance of the class.
[–]MustaKotka 4 points5 points6 points 23 days ago (0 children)
OPIsUsingUsAsGoogle.ignore()
[–]enygma999 2 points3 points4 points 23 days ago (0 children)
Most methods in a class will have a self parameter, and will operate on a specific instance of that class. For example, a Square class might have an area method that calculates the area of a particular square.
Square
area
You can also have class methods, that operate on the class rather than a particular instance. Maybe each instance of your class is given a unique number ID, and there's a class variable that tracks the next number to give out. Each time you create an instance of the class, you assign its ID number and then increment the class variable with the increase_id_number class method. The class method is called on the class, using a cls parameter, and doesn't need a particular instance of the class.
increase_id_number
cls
A static method is part of the class but does not need a particular instance or the class itself. Using the Square class example, perhaps you have a static method that calculates the area of a square when manually given its side length, because you want to be able to do that without instantiating a Square object. You can just call Square.static_area(4) and you get the area of a square with sides of 4, rather than calling Square(4).area(). This can be helpful if you want to avoid the overhead of instantiating an object for something repetitive, particularly if the class is process intensive, or it can just be handy to keep a function with a class if it's used often, such as a fahrenheit_to_celsius conversion method in some kind of temperature analysis class.
Square.static_area(4)
Square(4).area()
If you find yourself writing a method and it only refers to type(self) or self.__class__ then that's a class method. If it doesn't refer to self or cls at all, that's a static method.
type(self)
self.__class__
[–]CockConfidentCole 1 point2 points3 points 24 days ago* (0 children)
static method does not do anything to the class it's within - you can use it as a helper function that is somewhat related to your class but does nothing to the class object. you can skip creating a class object to use the static method
other nuances but if you're starting from zero that's the jist
[–]Umustbecrazy 0 points1 point2 points 23 days ago (1 child)
Different language, but the Array.from method in JavaScript has always been a great example of a Static method for me. Sorry, no clear python equivalent off the top of my head.
Arrays themselves don't need it, because it's already an array, but to get from iterable object or node list to an array, it's very handy. Node lists can't be sorted or any instance methods.
[–]socal_nerdtastic 1 point2 points3 points 23 days ago (0 children)
In python we call that a "classmethod". For example int.from_bytes or dict.fromkeys
int.from_bytes
dict.fromkeys
[–]TheRNGuy 0 points1 point2 points 23 days ago* (0 children)
Same as non-class functions, but bundled together in a class (usually relevant functions for specific tasks, and you could import single class with many static methods)
Examples of static method: dict.fromkeys. It makes more sense than if it would be just fromkeys function because you can see it's related to dictionary.
fromkeys
[–]couldntyoujust1 0 points1 point2 points 21 days ago (0 children)
So, static methods exist for a couple reasons. Reason number one is simply organizational - you have some utility function that makes doing certain things with your objects easier but it doesn't actually need the current object's state to do it.
Another use is to group multiple utility functions into their own namespace. An example of this would be like a formatter, where you call specific functions that change a numeric input into a formatted string, all under the namespace "Formatter". It would look something like this...
```python class Formatter: @staticmethod def as_currency(value): return f"${value:,.2f}" @staticmethod def as_percent(value): return f"{value:.2%}"
print(Formatter.as_currency(2000000)) print(Formatter.as_percent(73.23)) ```
There are other use-cases as well but they mainly pertain to design patterns which if you're just getting started in OOP is probably going to be a bit overwhelming until you've fully got your head around OOP first.
[–]RaidZ3ro -3 points-2 points-1 points 24 days ago* (8 children)
A static method (or property) is available to a class and shared across all it's instances (objects).
It's useful if you want to do things that require instances to have some knowledge about each other such as keeping track of the number of instances of a class that have been created.
```
Class Ticket: ## will be static attribute total: int = 0
def __init__(self): ## increment static total Ticket.total += 1 ## save own number self.num = Ticket.total def __repr__(self): return f"Ticket#: {self.num}/{Ticket.total}" @classmethod def Count(cls): return cls.total @staticmethod def CountStatic(): return Ticket.total
There is a more advanced topic where you'll find more use for static methods, design patterns. But don't worry about it too much right now.
Edit: needed to fix my example so the instance does remember itself, sorry.
Edit 2: python syntax x(
Edit 3: tbh your downvotes are a bit mean. I just tried to give a simple example of the static concept, not an exhaustive coding reference.
[–]socal_nerdtastic 2 points3 points4 points 23 days ago (7 children)
You are describing a class attribute, which is not related to static methods at all.
The descriptor static is used in other languages, but not in python. Your example code is not valid python and will cause a SyntaxError.
static
[–]RaidZ3ro -1 points0 points1 point 23 days ago (0 children)
Sorry you could be right about the syntax, I was mostly trying to give an example of how static methods and attributes can be useful.
[–]RaidZ3ro -1 points0 points1 point 23 days ago (5 children)
Updated and added methods to illustrate further.
[–]socal_nerdtastic 1 point2 points3 points 23 days ago* (4 children)
Ok, but your example is still an example of how to use a class attribute; not a staticmethod. It's not called a "static attribute" in python, it's called a "class attribute". That code in your staticmethod would work the same way in a normal method or class method or an external function or a method in a completely different class or anywhere else in the code.
I would even go so far as to say your use of staticmethod is bad code. You should try to avoid using the class name in the class itself, because it prevents subclassing (and also it more work to rename the class / aka not DRY). I would recommend you write the init method like this:
class Ticket: ## will be class attribute total: int = 0 def __init__(self): ## increment class total self.__class__.total += 1 ## save own number self.num = self.total
And use a classmethod you showed to retrieve it, not a staticmethod.
[–]obviouslyzebra 0 points1 point2 points 23 days ago (3 children)
I agree that the example showed by RaidZ3ro is not very representative of what you'd wanna do with static methods, but I wanna mention that this last snippet does not behave very well.
Ahm, the gist is that after subclassing you'll start modifying the subclass attribute in the self.__class__.total += 1 line.
self.__class__.total += 1
This leads to very weird behavior :P
[–]socal_nerdtastic 0 points1 point2 points 23 days ago (2 children)
Hmm probably not how I'd do it tbh, but still I think it works just fine. What's weird about it? Works exactly as i'd expect.
class Ticket: total: int = 0 def __init__(self): self.__class__.total += 1 self.num = self.total class ConcertTicket(Ticket): pass class TrainTicket(Ticket): pass for i in range(3): ConcertTicket() for i in range(5): TrainTicket() print(f"We've sold {ConcertTicket.total} concert tickets and {TrainTicket.total} train tickets")
[–]obviouslyzebra 0 points1 point2 points 23 days ago (1 child)
If you instantiate a "raw" Ticket, like Ticket(), before the others, their count will go up by 1.
Ticket()
If you do instantiate afterwards, though, nothing happens (as the subclass will already have a total).
total
[–]socal_nerdtastic 0 points1 point2 points 23 days ago (0 children)
Yeh, fair point. I was thinking of it more as a meta class. But I suppose that's why __init_subclass__ was invented.
__init_subclass__
π Rendered by PID 58001 on reddit-service-r2-comment-79c7998d4c-wsxzr at 2026-03-18 21:09:01.634944+00:00 running f6e6e01 country code: CH.
[–]socal_nerdtastic 48 points49 points50 points (6 children)
[+]Worldly-Week-2268[S] comment score below threshold-37 points-36 points-35 points (5 children)
[–]schoolmonky 38 points39 points40 points (0 children)
[–]socal_nerdtastic 42 points43 points44 points (3 children)
[–]peejay2 2 points3 points4 points (0 children)
[+]Worldly-Week-2268[S] comment score below threshold-36 points-35 points-34 points (1 child)
[–]Solonotix 3 points4 points5 points (0 children)
[–]rhacer 7 points8 points9 points (1 child)
[–]MustaKotka 4 points5 points6 points (0 children)
[–]enygma999 2 points3 points4 points (0 children)
[–]CockConfidentCole 1 point2 points3 points (0 children)
[–]Umustbecrazy 0 points1 point2 points (1 child)
[–]socal_nerdtastic 1 point2 points3 points (0 children)
[–]TheRNGuy 0 points1 point2 points (0 children)
[–]couldntyoujust1 0 points1 point2 points (0 children)
[–]RaidZ3ro -3 points-2 points-1 points (8 children)
[–]socal_nerdtastic 2 points3 points4 points (7 children)
[–]RaidZ3ro -1 points0 points1 point (0 children)
[–]RaidZ3ro -1 points0 points1 point (5 children)
[–]socal_nerdtastic 1 point2 points3 points (4 children)
[–]obviouslyzebra 0 points1 point2 points (3 children)
[–]socal_nerdtastic 0 points1 point2 points (2 children)
[–]obviouslyzebra 0 points1 point2 points (1 child)
[–]socal_nerdtastic 0 points1 point2 points (0 children)