首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >python嵌套类

python嵌套类
EN

Stack Overflow用户
提问于 2013-01-30 22:37:47
回答 1查看 31.7K关注 0票数 17

首先,这是我的测试代码,我使用的是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

当我这样做的时候:

a = account()
a.bank.balance

我期望得到balance的返回值,但是我得到了"balance“函数,为什么会这样?当我这样做时,它返回balance的值:

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

所以我想知道这是为什么,如果有人能想出一种方法,在嵌套版本中给我平衡的值,那就太好了。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-01-30 23:06:48

我的代码版本,带有注释:

#
# 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)
票数 31
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14606559

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档