python nested classes
My version of your code, with comments:
#
# 1. CamelCasing for classes
#
class Account:
def __init__(self):
# 2. to refer to the inner class, you must use self.Bank
# 3. no need to use an inner class here
self.bank = self.Bank()
class Bank:
def __init__(self):
self.balance = 100000
# 4. in your original code, you had a method with the same name as
# the attribute you set in the constructor. That meant that the
# method was replaced with a value every time the constructor was
# called. No need for a method to do a simple attribute lookup. This
# is Python, not Java.
def withdraw(self, amount):
self.balance -= amount
def deposit(self, amount):
self.balance += amount
a = Account()
print(a.bank.balance)
There are several problems:
- You're using the name
balance
for both the data member and for the function. - You're missing a
return
statement inbalance()
. balance()
operates on an instance ofbank
. There is no instance ina.bank.balance
: here,a.bank
refers to the inner class itself.
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.