somnambulist
somnambulist

Reputation: 31

Are all methods are preceded by a dot(.) or just some of them. How do we define it needs a dot or not?

I was learning Python by using Python Crash Course and came upon this String and Method thing: It only said that the dot(.) after name in name.title() tells Python to make the title() method act on the variable name.

Upvotes: 0

Views: 246

Answers (2)

S.B
S.B

Reputation: 16526

Not always, you can create a method dynamically:

from types import MethodType

def fn(x):
    return x.var

class A:
    def __init__(self):
        self.var = 20

obj = A()

method_ = MethodType(fn, obj)
print(method_)
print(method_())

output :

<bound method fn of <__main__.A object at 0x000001C5E3F01FD0>>
20

A method is an instance of type MethodType and also it has an object bound to it, when method gets called, it's first parameter will always get filled with that object. Here fn() function's first parameter (x) will be filled with obj object.

Upvotes: 2

Ajay Singh Rana
Ajay Singh Rana

Reputation: 573

The above answer is precise but i wanted to add to it.

Actually methods are functions that take objects as arguments and then return values based on that and as python is an Object Oriented Language therefore everything in python is an object.

When you call name.title(): then, python search for the title() method for the name object.And as all methods are designated to take the object as an argument:

`def title(self):
    ...+
`

This is what a method definition look like inside a class and the self argument here stands for the object calling the method. And we do not have to specify it explicitly it is recognised by the python interpreter.

As in your case: name.title() the object calling the method title() is the name variable therefore here self is assigned the value of name that is the function call name.title() is equivalent to title(name) but the former is the correct syntax of calling the method whereas the latter one is for comprehesion purpose.

If you run title(name) it surely gonna raise an error. But, as the title() method belongs to the str class you can always call str.title(name).

Hope i didn't confuse you instead of making it clearer...Happy coding..:)

Upvotes: 0

Related Questions