-1

I apologise in advance that this is a really nooby question. Just out of curiosity, what is the difference between (for example) function(a) and a.function()? Thanks for any answers.

Bill Reason
  • 391
  • 1
  • 5
  • 13

2 Answers2

1
class Example():
    def __init__(self):
        self.x = 1

    def change_x(self):
        self.x = 5
        print(self.x)

def example_function(x):
    print(x)

a= Example()
a.change_x()  #calling the object function of 

example_function("hello")  #calling the function in scope

#prints >> 5
#       >> hello

When you something.function() you are calling the function of that object.

When you are function() you are calling the function within scope that is defined in your namespace.

MooingRawr
  • 4,901
  • 3
  • 24
  • 31
1

The difference between function(a) and a.function() is the difference between a function and a method. A function is called function(a) and is not called on a variable. a.function() is actually a method and is called on an instance variable. When a.function() is called, whatever class a is, has a method function() that can be called on that variable. Whereas, when function(a) is called, a function is called with a as the parameter. An example of this is

' '.join(['a','b','c'])

The method join is called on the string ' ' (as join is a method that belongs to the str class) and takes the parameter ['a', 'b', 'c'].

Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61