Python Forum

Full Version: Understanding Method/Function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Am I understanding this correctly? A method is basically a function within a class, whereas a function is a separate entity able to be called globally
Yes can say it like that,but a method belong to the class as it takes class instance(self) as its first parameter.
A normal function can be placed in a class bye using @staticmethod
Example:
class Foo:
    def __init__(self, number):
        self.number = number

    def calc(self):
        '''A method in class Foo'''
        return 40 + self.number

    @staticmethod
    def bar():
        '''
        A normal function placed in class Foo
        I knows nothing about the class or instance
        '''
        return 100
Use class:
>>> obj = Foo(2)
>>> obj.calc()
42

# Call function directly 
>>> Foo.bar()
100
>>> # Can also be called from object
>>> obj.bar()
100
>>> 
#snippsat Thank you, easily understood.