I don't understand when to use empty brackets, dot notation ans such


#1

hi, this is a bit of a general question.
i find that many of my errors come from using dot notations when i should us brackets, or not putting empty brackets () when needed and such.

the reason is that i don’t really understand when to use either, it seems arbitrary.

is there any easy way to remember it? the logic behind it? (what do empty brackets tell python??)

thank you!


#2

Let’s say we have a dictionary,

fruits = {
    'a': 'apple',
    'b': 'banana',
    'c': 'cherry',
    'd': 'date'
}

To access a value, use the key in a subscript on fruits.

print fruits['d']    # date

In a list we access values by their index:

>>> fruits_values = list(fruits.values())
>>> fruits_values[0]
'apple'
>>> 

Notice that keys are strings, in quotes, and indexes are integer. Both are subscripts always written in square brackets.

As for dot notation and empty brackets (parens), dict is a class of Python objects with a dedicated set of methods, such as values() above. The dot tells Python that values is a method of a dict object.

object_of_a_class.method_of_the_class()

The empty parens are needed to invoke the method on the object (execution context). As we’ve seen above, the method returns a dict_values object which we converted to an indexable list.

A method is the same thing as a function when it comes to the mechanics except a method is inherited from its class and can only be invoked on an object of that class. Sometimes there is no parameter other than self which is the context object of the instance. This will become more clear with study and practice.

A function may operate without parameters or with them. The parameters are written in the parameter list

>>> def length(string_or_list):
    count = 0
    for x in string_or_list:
        count += 1
    return count

>>> length(fruits_values)    # function(arguments)
4
>>> 

If we leave out the arguments list on the function, we copy the function, rather than invoke it. The copy is invokable just as the original function.

>>> object_size = length
>>> object_size(fruits_values)
4
>>> 

This is a pretty generalized explanation but should help with your question.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.