Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics (2015) Python Data Types Strings

Adam Cameron
.a{fill-rule:evenodd;}techdegree seal-36
Adam Cameron
Python Web Development Techdegree Graduate 16,731 Points

Question about different types of functions

The Python docs are no help (are they ever any help to non-professionals?) so I'm gonna try asking here - can someone break down/point me to literature explaining why some functions attach to strings with .function_name() and some require you to pass the string as an argument like function_name(string)? Is it just arbitrary or is there some reason for this? I think understanding would help me avoid careless mistakes later.

2 Answers

.function_name() are called methods and function_name() are called functions.

The answer is a little technical, and it will be covered in detail in a future course.

Think of making a string. This is basically making an instance of the class String.

A class is like a model, or, if you'd like, a blueprint. Think of a class as a cookie cutter. You can use the cookie cutter to make cookie instances, but you can't use the cookie cutter itself for eating. You only eat the instances (the cookies you make with the cookie cutter) of the cookie cutter class.

Now, back to strings. There's a String class behind the scenes in Python. When we make a new string by using "Hello", we are simply creating an instance of the String class.

Classes have what's called an instance method, which is a method that can be called on an instance. You use a period to separate the name of the method with the instance. Here's an example: "Hello".split() We are calling the split() method on the string instance. Remember, we use a period/dot to separate the two! The period is basically saying: Use the method on the right to call the instance on the left!

So, basically "Hello".lower() is calling the lower() method on the "Hello" instance. Just repeating :smiley:

I hope this clears things up. Don't worry if this is still confusing, as classes is the hardest thing to learn for most students, including myself. This all will be covered in a future course! :smile:

I hope this helps :grin:

Happy coding! :tada:

:dizzy: ~Alex :dizzy:

No problem :)