5.6. OOP Self

  • Calling method on an instance

  • Calling function on a class and passing instance as an argument

  • Both are equivalent

5.6.1. Instance Name

  • Usually first parameter of a method is named self (PEP8)

  • But it can be named differently

>>> class User:
...     def __init__(instance, firstname, lastname):
...         instance.firstname = firstname
...         instance.lastname = lastname
...
...     def login(instance):
...         print(f'User login: {instance.firstname} {instance.lastname}')
>>>
>>> mark = User('Mark', 'Watney')
>>> mark.login()
User login: Mark Watney

5.6.2. With Self

>>> class User:
...     def login(self):
...         print('ok')

Calling function on a class:

>>> User.login()
Traceback (most recent call last):
TypeError: User.login() missing 1 required positional argument: 'self'

Calling method on an instance:

>>> User().login()
ok

5.6.3. Without Self

>>> class User:
...     def login():
...         print('ok')

Calling function on a class:

>>> User.login()
ok

Calling method on an instance:

>>> User().login()
Traceback (most recent call last):
TypeError: User.login() takes 0 positional arguments but 1 was given

5.6.4. Passing Instance

  • Calling method on an instance is equivalent to calling function on a class and passing instance as an argument

Calling method on an instance is equivalent to calling function on a class and passing instance as an argument.

SetUp:

>>> class User:
...     def login(self):
...         print('ok')

Calling method on an instance:

>>> mark = User()
>>> mark.login()
ok

Or:

>>> User().login()
ok

Calling function on a class and passing instance as an argument:

>>> User.login(mark)
ok

5.6.5. Use Case - 1

Using instance method:

>>> str('Mark').upper()
'MARK'

Using class function:

>>> str.upper('Mark')
'MARK'

5.6.6. Use Case - 2

SetUp:

>>> data = ['Mark', 'Melissa', 'Rick']

Using instance method:

>>> ','.join(data)
'Mark,Melissa,Rick'

Using class function:

>>> str.join(',', data)
'Mark,Melissa,Rick'

5.6.7. Use Case - 3

SetUp:

>>> data = ['Mark', 'Melissa', 'Rick']

Using list comprehension and instance method:

>>> result = [x.upper() for x in data]
>>> list(result)
['MARK', 'MELISSA', 'RICK']

Using list comprehension and class function:

>>> result = [str.upper(x) for x in data]
>>> list(result)
['MARK', 'MELISSA', 'RICK']

Using map and class function:

>>> result = map(str.upper, data)
>>> list(result)
['MARK', 'MELISSA', 'RICK']

5.6.8. Use Case - 4

>>> class User:
...     def __init__(self, username):
...         self.username = username
...
...     def login(self):
...         print(f'User login: {self.username}')

Create users:

>>> users = [
...     User('mwatney'),
...     User('mlewis'),
...     User('rmartinez'),
... ]

Login all users:

>>> users = map(User.login, users)
>>> result = list(users)
User login: mwatney
User login: mlewis
User login: rmartinez