Python Forum
Understanding Method/Function - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Understanding Method/Function (/thread-8871.html)



Understanding Method/Function - robdhunter - Mar-10-2018

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


RE: Understanding Method/Function - snippsat - Mar-10-2018

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
>>> 



RE: Understanding Method/Function - robdhunter - Mar-10-2018

#snippsat Thank you, easily understood.