python nested classes
python, python-3.x
Solution
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)
Problem
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): self.balance = 100000 def balance(self): self.balance def whitdraw(self, amount): self.balance -= amount def deposit(self, amount): self.balance += amount ``` when I do: ``` a = account() a.bank.balance ``` I expected to get the value of balance returned, instead I get the function "balance", why is this? It returns the value of balance when I do: ``` class bank: def __init__(self): self.balance = 100000 def balance(self): self.balance def whitdraw(self, amount): self.balance -= amount def deposit(self, amount): self.balance += amount a = bank() a.balance ``` So I want to know why this is and it would be great if someone could come up with a way to give me the value of balance in the nested version.