python嵌套类

标签 python python-3.x

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

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

最佳答案

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

#
# 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)

关于python嵌套类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14606559/

相关文章:

python - 添加键的值并根据键在 Python 字典列表中的出现对其进行排序

python - 绘制 2 个 .dat 文件,字符串文件句柄错误

python - 如何使用 Python 将文本添加到多个图像

python-3.x - 如何发送多个收件人sendgrid V3 api Python

python - 如何阻止 's' 在我的循环中重复出现两次?

python - 在饼图上显示带有图例的数字 - Tkinter、Pyplot、Matplotlib

Python boolean 比较

python - 使用 Python Ctypes 将结构指针传递给 DLL 函数

python - 无法启动 Celery Worker (Kombu.asynchronous.timer)

python - 如何阻止 Matplotlib 导航工具栏缩放在绘图更新时重置?