Reputation: 129
I've noticed some functions are called using the var.func()
format as in var1.split()
while other functions are called using the func(var)
format as in sorted(list1)
.
Here's a very simple program to illustrate the question. I've also noticed the same behavior with open
and read
functions.
str1 = "This is a string"
list1 = str1.split()
print str1.split(' ')
print sorted(list1)
I'm very new to programming so any help would be greatly appreciated!
Upvotes: 0
Views: 85
Reputation: 129
Following TraxusIV's line of thought, I tried the following and it worked!
from string import split
str1 = "This is a string"
list1 = str1.split()
print split(str1)
print sorted(list1)
Upvotes: 0
Reputation: 661
In var.func()
the func()
is meant to be used with the var
object.
e.g. split()
on a string object but cannot use on a list
But func(var)
is not confined to a single var object type. you can use it with any appropriate var object.
e.g. sorted()
can be used with any iterable like lists
, tuples
, dicts
...
Upvotes: 0
Reputation: 1499
This difference has to do with issues of scope. Functions which can be called directly, such as sorted(list1)
in your example above, are either builtin functions, or else defined at the top level of one of your imported libraries (for example when using from simpy import *
, you can call test()
directly to run the built in test suite for the simpy library). Functions which are accessed through the dot operator are functions which are defined for the particular data type that you are applying them to. Remember that each data type in python is an object, and therefore an instance of a class. Those functions, such as split()
are defined in that data type's class definition. Additionally, to use the example of test()
from the simpy library again, if you were to import a library with only import simpy
, you would have to use simpy.test()
to call that method.
from simpy import *
test()
vs
import simpy
simpy.test()
The first works because you've imported all methods and classes from the top level of the simpy library, whereas the second works because you've explicitly dived into the scope of the simpy library.
Upvotes: 0
Reputation: 10199
var.func()
just means that the function belongs to the object.
For instance, x.sort()
. list
s (like x
) have a function sort
.
When you call func(var)
, func
is not a function of lists.
For instance, sorted(x)
.
This isn't Python specific. You will see the same idea in other languages (e.g. Java).
Upvotes: 0
Reputation: 1023
Everything in python is an object. Thus when doing something like this:
s = "some string"
s
is an str
object and you can call all the str methods on it. You can also do things like this:
"some string".split()
and it will give you a list of splitted strings.
Upvotes: 2