5.5. OOP Self
Calling method on an instance
Calling function on a class and passing instance as an argument
Both are equivalent
5.5.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}')
>>>
>>> obj = User('Alice', 'Apricot')
>>> obj.login()
User login: Alice Apricot
5.5.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.5.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.5.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:
>>> obj = User()
>>> obj.login()
ok
Or:
>>> User().login()
ok
Calling function on a class and passing instance as an argument:
>>> User.login(obj)
ok
5.5.5. Use Case - 1
Using instance method:
>>> str('hello').upper()
'HELLO'
Using class function:
>>> str.upper('hello')
'HELLO'
5.5.6. Use Case - 2
SetUp:
>>> data = ['Alice', 'Bob', 'Carol']
Using instance method:
>>> ','.join(data)
'Alice,Bob,Carol'
Using class function:
>>> str.join(',', data)
'Alice,Bob,Carol'
5.5.7. Use Case - 3
SetUp:
>>> data = ['Alice', 'Bob', 'Carol']
Using list comprehension and instance method:
>>> result = [x.upper() for x in data]
>>> list(result)
['ALICE', 'BOB', 'CAROL']
Using list comprehension and class function:
>>> result = [str.upper(x) for x in data]
>>> list(result)
['ALICE', 'BOB', 'CAROL']
Using map and class function:
>>> result = map(str.upper, data)
>>> list(result)
['ALICE', 'BOB', 'CAROL']
5.5.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('alice'),
... User('bob'),
... User('carol'),
... ]
Login all users:
>>> users = map(User.login, users)
>>> result = list(users)
User login: alice
User login: bob
User login: carol