Object Oriented Programming in Python: Class & Instance Variable

Ji Kim·2021년 2월 3일
0

Algorithm Concept

목록 보기
5/6

The previous post talked about namespace of class and instances and its relationship.

On this post, we will be learning about class variable and instance variable.

We will be making class Account with constructor (init) and destuctor (del). A constructor will be called once the instance is created and conversely, destructor will be called once the instance is deleted.

Input

class Account:
    num_accounts = 0 
    
    def __init__(self, name):
        self.name = name
        Account.num_accounts += 1
    
    def __del__(self):
        Account.num_accounts -= 1

Account has total two variables (num_accounts and self.name)

Class Variable : a variable declared inside the class (num_accounts)

Instance Variable : a variable declared by the creation of instance attached by self.

Now we will make two different instances lennon and starr.

Input

lennon = Account('lennon')
starr = Account('starr')

Input

lennon.name

Output

lennon

Input

starr.name

Output

starr

We can see that the instance variable name is correctly binded by the owner of the account.

Now, let us check the total number of accounts created so far.

Input

lennon.num_accounts

Output

2

Input

starr.num_accounts

Output

2

Although instance lennon and starr does not have variable num_accounts assigned to the instance namespace, since the class namespace has variable num_accounts, it returns value 2.

Input

Account.nums_account

Output

2

So as accessing the num_accounts from class!

profile
if this then that

0개의 댓글