python嵌套类

2024-06-11 21:56:45 发布

您现在位置:Python中文网/ 问答频道 /正文

首先,这是我的测试代码,我使用的是Python3.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,这是为什么?当我这样做时,它返回余额的值:

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

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


Tags: 方法函数selfinitdefaccountpassamount
3条回答

a.bank类(不是实例),因为您从未在a上创建过银行的实例。所以如果a.bank是一个类,a.bank.balance是绑定到该类的方法。

但是,这是有效的:

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

当然,当您显示没有嵌套类的工作代码时,它确实回避了这样一个问题:为什么要使用嵌套类。我认为非嵌套版本要干净得多。

有几个问题:

  1. 对数据成员和函数都使用名称balance
  2. balance()中缺少return语句。
  3. balance()bank实例操作。a.bank.balance中没有实例:这里,a.bank引用内部类本身。

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

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

相关问题 更多 >