Python Forum
Understanding Method/Function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Understanding Method/Function
#1
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
Reply
#2
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
>>> 
Reply
#3
#snippsat Thank you, easily understood.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Understanding a function ebolisa 3 752 Jul-14-2023, 06:03 PM
Last Post: snippsat
  i want to use type= as a function/method keyword argument Skaperen 9 1,771 Nov-06-2022, 04:28 AM
Last Post: Skaperen
  Building a method name in a function ffgth 9 3,130 Oct-19-2020, 01:21 PM
Last Post: buran
  Having hard time understanding the function self-returning itself twice jagasrik 2 2,448 Aug-15-2020, 08:50 PM
Last Post: deanhystad
  function/method help myv5285 3 2,740 May-17-2020, 04:19 AM
Last Post: buran
  Accessing method as function object ClassicalSoul 2 1,975 Feb-14-2020, 09:31 PM
Last Post: wavic
  function vs method prateekshaw 2 2,152 Nov-14-2019, 07:00 PM
Last Post: DeaD_EyE
  I'm trying to figure out whether this is a method or function call 357mag 2 2,378 Jul-04-2019, 01:43 AM
Last Post: ichabod801
  function method problems drchar 2 2,854 Dec-11-2018, 02:38 PM
Last Post: buran
  Seeking understanding with the python import function. Intelligent_Agent0 2 2,573 Feb-18-2018, 11:57 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020