繁体   English   中英

python嵌套类

[英]python nested classes

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

我希望得到平衡值的回报,而不是我得到的功能“平衡”,为什么会这样? 我这样做时会返回余额值:

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

所以我想知道为什么会这样,如果有人想出办法让我在嵌套版本中获得平衡价值,那就太棒了。

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

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

有几个问题:

  1. 您正在为数据成员和函数使用名称balance
  2. 你在balance()缺少一个return语句。
  3. balance()bank 实例上运作。 a.bank.balance没有实例:这里, a.bank指的是内部类本身。

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

当然,当您显示没有嵌套类的工作代码时,它确实引出了为什么要为此使用嵌套类的问题。 我认为非嵌套版本更清晰。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM