Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Skills:
LLM Engineering80%Prompt Craft70%Prompt Systems Engineering60%Tool Use & Function Calling50%
Key Takeaways
This video tutorial demonstrates the use of @classmethod, @staticmethod, and instance methods in Python Object-Oriented Programming (OOP) using Python 3.6, with examples of class methods as factory functions and static methods for independent actions.
Full Transcript
hey there it's Dan and today I want to talk about the difference between Class methods static methods and plain or regular instance methods in Python kind of demystify some of the differences between them when you would use each what are some of the common scenarios and how you can use them to actually make your code cleaner and more maintainable and easier to work with in the future okay so let's Jump Right In I want to make this really Hands-On and kind of work from a simple example that I can use to show you the difference so I created this uh class I called my class just a really simple example and um it's got a couple of different method Types on it so the first one is just called method or the method is called method and um it's just a plain instance method and you can see here it takes one argument the self argument which points to the object instance and um that means within method we can actually modify or um read attributes on the object instance and uh when you compare that to a class method so I just called this one class method and then use the class method decorator to actually mark it as a class method you can see here that the class method only has access to this class parameter this class argument it doesn't have have a self argument so this means a class method it can only access the the class itself or the object representing the class because well everything is an object in Python but um the key difference is that when I create an instance of my class and then call class method on it it won't be able to to actually access the self object right so it can only access attributes that actually exists on the class itself and not on the instance Now with uh static method again the approach is really similar you just you know Define a regular method and then Mark it with the ad static method decorator what you can see here is that it doesn't take any arguments at all so it has no access to the class or the object instance at all so it's completely separate from that and it's really just a way to name space your methods so now you know I know this this is uh very uh very theoretical at this point and it's it's going to become much more clear when we actually try and um do some experimentation with this stuff some Hands-On work so the first thing I want to show you here is that when I create an object instance based on this class I can actually call any of these method Types on that object so I I can call a plane method and I kind of structure these these methods in a way that they return a string that kind of explains what's going on right so when I call object. method we can see here that well we called the instance method and we had this self object pointing to an instance of um of my class now I can do the same thing with the class method and now when I call this you can see here that again we're calling this class method method and this time we also have access to this class object now the difference is that with the instance method we actually had access to the object instance right so this was an instance of a my class object whereas with the class method we have access to the class itself but not to any of the objects because the class method doesn't really care about uh an object existing however you can both call um class method and static method on an object instance is going to work it doesn't really make a difference so again when you call static method here it's going to work and it's going to know which method you want to call but really the key difference now is going to be that we can also say okay my class and I'm not creating an instance of this class um and I can go in and say um class method for example this is going to work fine I can also go ahead and say uh call call the the static method it's also going to work fine but of course when I try and call method that's going to fail because we didn't actually call it with a class instance so I hope this makes this distinction between regular methods and static and class meth methods a little bit more clear now of course the big question is okay why why do we need that right why why is that a thing and um I want to go over some examples here of um what you can use these methods for because I think they're actually a really powerful uh concept or a really powerful tool for you to structure your code in a way that makes the most sense okay so this is what I came up with the classical Pizza example for teaching object-oriented programming so what I've done here is I defined this really simple Pizza class um it's got a Constructor takes you know some well arbitrary ingredients object we're just going to assume it's some kind of list or container with these ingredients and I also put a repper on it so we can um nicely format it as a string and then here if you're wondering what that is so that is the new format strings in Python 36 which are really awesome so I highly encourage you encourage you to try that out you could just use regular format strings of course so okay so so basically what I did here I created this pizza class and now we can use it to create Pizza objects right and so um if I'm not mistaken that's a margarita um my wife's Italian You' probably kick my ass if I got that wrong but I think that's a margarita well what you've seen here is that we can create these pizza objects but as we create more and more complicated pizzas um and um like a prudo or something I don't know um maybe we need some um mushrooms on that as well right and and you can already tell I'm struggling with the naming here right I can cre create all of these wonderful pizzas here but I need to remember all of these ingredients so now it wouldn't be too much of a stretch to actually have like solve this problem with a static method okay so wanted to make it a little bit easier for us to create new pizza objects without having to remember all of these ingredients and so a really good way to structure this in my opinion is to actually use class methods to have different Factory functions for the different types of pizza you can create and I'm going to show you how this works in a minute now so what I'm going to do here is I'm going to define a margarita um class method here and then that's just going to create a new instance of the class and um let me just type that out here so what I'm doing here is whenever this Margarita method is called and we can call it on just a pizza class we don't actually need a real Pizza Pizza instance um I'm just going to call I'm going to create an instance of a pizza or you know whatever a class is named like the nice thing here is that I don't have to refer to the name up here so I can keep that name um just in one place and whenever I update that I don't have to worry about changing the rest of the code but um it's uh it's just going to use the class uh objects just going to call this init init method here and it's going to create a new pizza with these ingredients and so um this is kind of a really maintainable way to do these Factory functions so I could also have a prudo I didn't actually look the spelling up for this um right so if any Italians are watching this then let me know if I if I SC screwed this up so here we actually want cheese I guess that would be mozzarella right and not cheese but whatever it's it's a kind of cheese anyway this isn't about cheese this is about uh python so uh okay so I'm creating I'm creating a different kind of pizza here and now when I when I finish defining this class I can actually say hey I want a margarita and that returns a new pizza object right I could have also called this make margarita or or new Margarita or something like that right just to to kind of have a better naming scheme but um the same thing is going to work with the prudo and um I feel like this is a really good use for these class methods if you have classes with complicated Constructors you know that take a lot of arguments and you want to provide a simplified interface for your users then I think using a class method in this fashion can be really beneficial and it's just going to make the API a little bit easier for people to work with so this is one example of where I would use a static method I mean of course you could always argue that you know maybe this should be a separate function y y y but I think in some cases this could really work well if you if you structure your um your classes that way up next when to use static methods so um it's it's a little bit hard to come up with a really simple example here but you know I'm going to keep stretching the pizza the pizza thing here so okay so this is what I came up with um basically a static method doesn't have access to the class or the um object instance at all right and now that's a pretty big limitation but it it's also really good signal to um well to to show that a particular method is um is really independent from everything else around it right so for example if I Flack this as a static method it's pretty clear that this method it it's probably not going to change the the object or the class in any way because it it's not really meant to have access to it I mean sure you know you could work around that and could kind of work with a global variable but in general like it's a pretty good hint that this is a self-contained method which has all kinds of benefits for later testing this thing and just kind of understanding the limitations of this method and so in some cases can really be helpful to make your code easier to maintain in the future because you're really communicating this intent right where you can someone else reading this code can pretty clearly understand that um in this case our little circle area function here it's not to modify the state of this object itself so um let me walk you through this example real quick so basically what I've added here well I kind of changed the Constructor around a bit so now we've got a radius uh argument here for the pizza as well forgot to update the repper but you know doesn't really matter for now and then I added this area function and um well I could have just C calculated the area of the pizza directly in here but I you know wanted to have a static method in there and so basically what I did there instead of calculating the area directly with with an expression here um I'm just offloading that to the circle area function and then the circle area function just takes an R which is the radius and uses the classic um R squar time * pi formula to calculate the circle area so you know this is honestly like kind of a simplistic example and you usually wouldn't implement it like that but it goes to show the concept and now what happens here is I can instantiate um a pizza so for example you know this is a really sad pizza with like 4.5 um well we don't have a unit on that right let's say meters um a giant pizza cheese only and we're going to create this this object this pizza object and then we're going to call the area function on it and it's going to give us this um this result so the way this is calculated is that area actually Forks off the all that work to the circle area function and now the circle area function is actually completely independent and I also used uh a single underscore to mark it as kind of not part of the public API of this class um but kind of an internal implementation detail um but nevertheless now the cool thing is that we have this circle area function that um is completely independent from the rest of the object and it can't actually modify the object State and um this is a pretty good hint for someone else reading the code and it also simplifies testing right because when I write my tests for this then um I don't have to worry about instantiating a pizza object making sure it doesn't get modified because the circle area helper it can't do that right and so um I occasionally use static methods to communicate that intent and to keep my helper functions um nice and clean and make sure that they're not modifying the object State all over the place again just a quick recap so we talked about plain methods class methods and static methods when you can call them pretty much all you need to remember is that a regular method needs an object instance to be called on and in a class method it needs a class and it has access to the class and a static method doesn't really have any access to the object or the an object instance or the class uh at all and it's just kind of a way to namespace your functions all right so have fun exploring the the pizza analogy here and building the perfect Pizza API in an object-oriented fashion um talk to you soon and happy python
Original Description
https://dbader.org/python-tricks ► Master OOP techniques in Python with bite-sized code examples
What's the difference between @classmethod, @staticmethod, and "plain/regular" instance methods in Python? You'll know the answer after watching this Python video tutorial:
Regular (instance) methods need a class instance and can access the instance through `self`. They can read and modify an objects state freely.
Class methods, marked with the @classmethod decorator, don't need a class instance. They can't access the instance (self) but they have access to the class itself via `cls`.
Static methods, marked with the @staticmethod decorator, don't have access to `cls` or `self`. They work like regular functions but belong to the class's namespace.
In this video tutorial I go over the differences between these different kinds of methods in Python. I also explain when to use each with a simple example so you can improve your object-oriented programming (OOP) skills in Python.
To learn how to use the full potential of Python check out "Python Tricks: The Book" at the link below.
FREE COURSE – "5 Thoughts on Mastering Python" https://dbader.org/python-mastery
PYTHON TRICKS: THE BOOK https://dbader.org/pytricks-book
SUBSCRIBE TO THIS CHANNEL: https://dbader.org/youtube
* * *
► Python Developer MUGS, T-SHIRTS & MORE: https://nerdlettering.com
FREE Python Tutorials & News:
» Python Tutorials: https://dbader.org
» Python News on Twitter: https://twitter.com/@dbader_org
» Weekly Tips for Pythonistas: https://dbader.org/newsletter
» Subscribe to this channel: https://dbader.org/youtube
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Real Python · Real Python · 41 of 60
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
▶
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
A better Python REPL – bpython vs python interpreter
Real Python
Introducing large-type.com – A Utility Website
Real Python
Reading Hacker News Without Wasting Tons of Time
Real Python
Forward References and Python 3 Type Hints
Real Python
Using Sublime Text as your Git Editor
Real Python
Python Code Linting and Auto-Complete for Sublime Text
Real Python
Make your Python Code More Readable with Custom Exceptions
Real Python
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
How to Use Sublime Text from the Command Line
Real Python
Rename Variables with Multiple Selection in Sublime Text
Real Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
Sublime Text Whitespace Settings for Python Development
Real Python
Function Argument Unpacking in Python
Real Python
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
Using "get()" to Return a Default Value from a Python Dict
Real Python
A Python Shorthand for Swapping Two Variables
Real Python
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
Setting up Sublime Text for Python Developers
Real Python
Sublime Text + Python Guide Overview
Real Python
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
Type-Checking Python Programs With Type Hints and mypy
Real Python
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
My Python Code Looks Ugly and Confusing – Help!
Real Python
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
Programmer Portfolio – Example and Walkthrough
Real Python
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
How to Build Your Public Speaking Skills as a Developer
Real Python
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
Cool New Features in Python 3.6
Real Python
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
Emulating switch/case Statements in Python with Dictionaries
Real Python
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
A Crazy Python Dictionary Expression ?!
Real Python
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
Optional Arguments in Python With *args and **kwargs
Real Python
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
Installing Python Packages with pip and virtualenv / venv
Real Python
"For Each" Loops in Python with enumerate() and range()
Real Python
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
Python Tutorial: List Comprehensions Step-By-Step
Real Python
Leveraging Python's Implicit "return None" Statements
Real Python
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
Writing automated tests for Python command-line apps and scripts
Real Python
How to find great Python packages on PyPI, the Python Package Repository
Real Python
Immutable vs Mutable Objects in Python
Real Python
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
My Experience at PyCon 2017 in Portland
Real Python
Pylint Tutorial – How to Write Clean Python
Real Python
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python
More on: LLM Engineering
View skill →Related AI Lessons
⚡
⚡
⚡
⚡
X now offers an MCP server to make its platform easier for AI tools to use
TechCrunch AI
n8n Automation Repurpose Video Content: The 2025 Production Guide
Dev.to AI
You’re Still Paying $200/Month for AI Tools You Could Replace With a Free Local Setup Tonight
Medium · Data Science
Top 10 AI Tools Every College Student Should Know in 2026
Medium · AI
🎓
Tutor Explanation
DeepCamp AI