python nested classes

后端 未结 3 630
甜味超标
甜味超标 2020-12-29 07:17

First of all, here\'s my test code, I\'m using python 3.2.x:

class account:
    def __init__(self):
        pass

    class bank:
        def __init__(self):         


        
3条回答
  •  长发绾君心
    2020-12-29 07:50

    a.bank is the class (not instance) since you've never created an instance of the bank on a. So if a.bank is a class, a.bank.balance is a method bound to that class.

    This works however:

    class account:
        def __init__(self):
            self.bank = account.bank()
    
        class bank:
            def __init__(self):
                self.balance = 100000
    
            def whitdraw(self, amount):
                self.balance -= amount
    
            def deposit(self, amount):
                self.balance += amount
    
    a = account()
    print a.bank.balance
    

    Of course, as you show working code without nested classes, It really begs the question about why you want to use nested classes for this. I would argue that the non-nested version is much cleaner.

提交回复
热议问题