Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics (Retired) Shopping List Lists

Henning Holm
Henning Holm
4,163 Points

Difference between writing something before a command and after.

Why are some cmd like "split" done by writing, for example my_sentence.split() and not like split(my_sentence)? How can we know when to put something before, like: something.cmd and when in parentheses like: cmd(something) ?

2 Answers

Josh Keenan
Josh Keenan
19,652 Points

Hey Henning, great question.

A command as you put it with a . is a method.

One without is a function in built to Python or one that you made yourself.

If you are using string.lower() for example, you are using the method .lower() on a string, a method is a function defined within a class (you learn all about it later in the track!). This means only something of that class or a child class can use this method, ie. an integer can't use .lower().

Want to go further down the rabbit hole or is that okay?

Chris Freeman
Chris Freeman
Treehouse Moderator 68,404 Points

Down the "rabbit hole"....

There isn't a practical* use for this, but for fun, it is possible to access the split() functionality stand-alone (sort of). The class method str.split() can be called on a object. Furthermore, if you just "have to have" a split() function you can define it yourself.

$ python3
Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
# define a string
>>> string = "Split this string"

# split string using class method
>>> str.split(string)
['Split', 'this', 'string']

# show no split() function defined
>>> split()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'split' is not defined

# define split function
>>> def split(obj):
...     return str.split(obj)

# split string using new function
>>> split(string)
['Split', 'this', 'string']

* Using the str class method split on an object of the same class instead of using the instance method (obj.split()) does not a practical use unless this particular str instance had overwritten the inherited class method and you needed to run class version instead.

Henning Holm
Henning Holm
4,163 Points

Okei, thanks!! Helped me understand a bit more, but I guess this will be even clearer as I progress through the course :)