I was watching Learn Python - Full Course for Beginners [Tutorial] on YouTube here.
At timestamp 4:11:54 the tutor explains what a class function is, however from my background in object oriented programming using other languages I thought the correct term would be method?
Now I am curious if there is a difference between a class function and method?
CodePudding user response:
They are wrong. But, it's a minor confusion they made and doing video courses which involves speaking and typing can be certainly challenging. No big deal.
When the function belongs to a class, it's a method (a more specialized form of a function). When it's outside of a class it's a function.
How do I know they are wrong?
You use this syntax to create one in Python:
class SomeClass:
@classmethod
def the_method(cls, vars):
....
def instance_method(self, vars):
...
It's not a @classfunction
decorator. It's a @classmethod
decorator.
See the docs at https://docs.python.org/3/library/functions.html#classmethod
CodePudding user response:
Method is the correct term for a function in a class. Methods and functions are pretty similar to each other. The only difference is that a method is called with an object and has the possibility to modify data of an object. Functions can modify and return data but they dont have an impact on objects.
Edit : Class function and method both mean the same thing although saying class function is not the right way to say it.
CodePudding user response:
Michael’s answer - upvoted - covers the syntax of classmethods, which are a thing. No need to repeat it. I’ll focus on why you’d use @classmethod.
You dont need to create an instance with a classmethod. Formatter.format(“foo”) vs Formatter().format(“foo”).
That also means you cant store state/configuration on the instance because there is no instance. Also inheritance and polymorphism may not work as well (at all?) with classmethods - i.e. if I was planning to bring them into play on a classmethod I’d be very cautious about actual behavior.
In practice you usually want to use regular methods, except on class methods that create instances (which are often called factory methods). If you really don't need an instance, maybe a standalone function would do the job just as well? Python does not require functions to live only on classes (like Java).
As far as terminology goes, don’t sweat it besides exam considerations. Method vs function are not that different except that one has an instance (or the class in a @classmethod) as first argument.