Why do some methods use dot notation when others don’t?

Question

Why do some methods use dot notation when others don’t?

Answer

Python is an object-oriented language, meaning it’s built around the idea of objects making things more scalable and reusable. You’ll be introduced to objects in depth later in the course, but for now think of objects as being built from blueprints that specify that object’s properties and methods.
Dot notation allows us to use methods belonging to an object. For example, if we had a Car object it might have an ignition( ) method that we can use to turn the car on. Strings are objects just like a Car could be, and they have methods you can make use of, like upper( ) and lower( ).
Other methods that don’t use dot notation are not dependent on being attached to an object, and might even be built into the language, like the len( ) method you learned about!

25 Likes

An easier way to think about it would be that the methods using dot notation do something to the variable while the others tell us something about it.

152 Likes

In the course it is mentioned that
Methods that use dot notation only work with strings.

On the other hand, len() and str() can work on other data types.

So can you give some example on the the behalf of above mentioned statements

3 Likes

that is not entirely true, there are also methods for other data types:

print ['a', 'b', 'c'].pop(1) # will output: b

so methods are data type specific while built-in function will work on multiple data types:

len("string")
len(['a', 'b', 'c'])

you will grasp this better once you learned about functions, classes and methods

7 Likes

2 posts were split to a new topic: The len() built-in function

Is that strictly true since str() would do something with the variable by turning it into a string, rather than just tell us something about it like len() may do?

3 Likes

str() doesn’t actually change the variable, but tells us what the string version would be, so it’s still telling us something about the variable.

5 Likes

Why do we use empty parenthesis “( )” in using dot notation?

calling functions and methods requires parenthesis. The parentheses don’t have to be empty, for example:

console.log('hello world');

we use the dot notation (log is a method of console object), and we supply an argument between the parentheses (hello world)

2 Likes

Methods are blocks of code that are associated with an object. They are called using dot notation, the object name first: obj.method(). sort(), for example, is a method belonging to the list object, and it is called using my_list.sort(), sorting the list in place.

Functions are stand alone objects. They are called without any association to an object, and generally work with a variety of objects. sorted(), for instance, is a function. It works on any iterable, and returns a new, sorted version of the iterable.

If you call a method or function using the parentheses, the interpreter assumes that you want to run the function or method.

If you call a method or function without parentheses, the interpreter assumes that you want to return the function or method.

>>> my_lst = [5,3,2,6]
>>> s_lst = sorted(my_lst)
>>> print(sorted)   # no parentheses
<built-in function sorted>
>>> print(s_lst)
[2, 3, 5, 6]
>>> print(my_lst)
[5, 3, 2, 6]    # unchanged
>>> my_lst.sort()
>>> print(my_lst)
[2, 3, 5, 6]     
>>> print(sort)  # no parentheses, no object
Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    print(sort)
NameError: name 'sort' is not defined
>>> print(my_lst.sort)    # no parentheses, object specified
<built-in method sort of list object at 0x00000241AF652B48>
>>> 

You can obtain a list of built-in functions by typing dir(__builtins__) at the >>> prompt in a shell. For a list of the methods of an object, type dir(obj) where obj is the object name (list, str, int) , or any object of the type, i.e., dir(‘abc’) for a list of string methods.

1 Like

What about .isalpha() and .isdigit()? .They don’t seem to modify the strings they were called on. It would be nice if it were that simple, but it doesn’t seem to be.
The input() method doesn’t tell you anything about its prompt - it returns the user’s input. I suppose that is somewhat of a fair “exception”, though.
The print() method doesn’t tell you anything about the data it is called on (strictly speaking - we’re talking about return values, right?).

print() specific details

If you print the result of a print statement, the inner print statement will still executed, and then you get None because that inner print statement returned nothing (technically, it returned None) to the outer print function.

You might go on to argue that it doesn’t modify the data either. That would also be correct. I didn’t say that it had to be one or the other - I was simply saying that it doesn’t seem to be that simple.

Also, instead of writing len("hello") I could write "hello".__len__() which is still only telling me the length (to be fair, this isn’t a “regular” case).

Another “exception” to this is the .split(separator) method. Test it out. It doesn’t modify a string at all. Instead, it creates a list of strings. If you don’t assign that list to anything, then the information is just lost because it’s useless.

Since .split() doesn’t modify a string, .join() just had to join the fun. It’s called on a string that doesn’t get modified. Its parameters don’t get modified either! It just creates a string that is a chain of all its arguments, separated by the given separator.

In short, there are multiple methods that don’t follow this “rule” and there are probably many more. I personally don’t have a shortcut way of memorizing it, other than the fact that there are a billion string methods in just about every language. If you just keep using a language, you’ll see patterns in certain places.

That’s a fair question. The short and simple answer is that what I stated is a rule of thumb. It’s right in most cases, but it’s not always. I have a more complicated summing up, but it’s not as easy to understand. Here it is:

Functions using dot notation are attached to a specific object and will only work on that object. Multiple objects can have a function that does the same thing (e.g., all strings have a .upper() function), but if you tried to use .upper() on a non-string, it would tell you that the function doesn’t even exist. This is because the .upper() function has not been assigned to non-strings. You could assign a .upper() function to it, but it is not built in (and it wouldn’t do the same thing).

Functions without dot notation are general functions that can usually be passed any object. For example, the len() function can be used on strings, arrays, lists, dictionaries, etc. and will still work fine. It is not restricted to one data type.

So, is my “rule” true? No. But it’s usually the case. In most cases that a function is only assigned to one data type (dot notation), it’s because you’re altering the data in a way that wouldn’t make sense in other data types. Most of the time that you use a method, it’s because you’re getting information that exists in many different data types.

But there are exceptions. There is information about a string that would make sense about an integer, and there are things you can do to a string that you can also do to an integer.

Let’s test my more complicated rule on your examples:

.isalpha() would not make sense in any context but a string (why would you ask an integer or array if it is made of letters of the alphabet?) so it uses dot notation

.isdigit() would not make sense in any context but a string (an integer or float will always be made of digits, and others will not be) so it uses dot notation

input() works on most data types, so it should be a method.

print() works on most data types, so it should be a method.

I’m not going to argue your len() example since, as you stated, that’s not a usual use. I’m not sure what’s going on there. (Maybe the double underscores signify that you’re calling a method? I really have no idea. Might make a good google search)

.split() and .join() don’t make sense in any context but strings, so they use dot notation (they might make sense in the context of arrays, lists, etc., but they would go about it in completely different ways, so you couldn’t use the same method)

I hope that clears things up a bit. Maybe I should have stated that there are exceptions in my first message, but I think it’s simpler for people to see at first a rule of thumb. If they’re interested, I guess they can now read on to this. :slight_smile:

(Just a warning: my python’s a bit rusty. I might have accidentally said something from JS. Please forgive me. They’re not extremely different, so hopefully, the idea I’m trying to get across will still make sense if that happens)

1 Like

I wasn’t really confused in the first place, just curious about how much that applies, but I do think that is a much clearer explanation and is a good way of relating objects, methods, and dot notation - methods with dot notation are called on a specific data type (including a user-created class) because they wouldn’t make sense on other data types, while those without dot notation are more general and can be called on a variety of data types. Methods without dot notation are also used for things more complicated than that, but it’s a generally good way of understanding it.

Your ‘rule of thumb’, in general, describes the result of the use of dot notation pretty well, but it can still be important to keep in mind that it’s not necessarily true for every single method.

details on .__len__() example

As for that example, I’m near certain that calling thing.__len()__ is equivalent to len(thing). I think it has something to do with how Python is built, and I think that behind the scenes len(thing) is actually thing.__len()__ - I could be wrong though, so don’t take my word for it.

some irrelevant-to-main-point notes

If you write a float as a string and then call .isdigit() on it, it will actually return False, because the decimal point/period, ., is not a digit. Then again, if you really wanted to know if it’s an integer, you can just ask it for its type (which ends up being a method that follows your ‘rule’).

So… in summary - your rule of thumb does work pretty well for people (especially those new to programming) to remember what uses dot notation and what doesn’t, but it can cause confusion in some cases. However, your deconstruction of what each method is for and how that influences whether or not it is written with dot notation is, in my opinion, a clearer and more accurate explanation that helps deeper understanding. :slight_smile:

>>> dir(str)

The above will output a list of all the attributes of the str class. Atributes that behave as functions are methods of the class.