首页 > 解决方案 > Python 类 <__main__.Credit at 0x> 问题

问题描述

我正在练习python类继承。但我发现了一些奇怪的东西。当我继承父类并尝试检查属性时。我无法访问第一个属性,它总是返回内存位置。我无法弄清楚背后发生了什么。希望寻求一些帮助。谢谢你。

这是我的代码:

class Account():
def __init__(self, acct_num, open_deposit=100, overdraft_limit=1000, interest_rate=1):
    self.number = acct_num
    self.balance = open_deposit
    self.limit = overdraft_limit
    self.interest = interest_rate

def __str__(self):
    return f'The balance is {self.balance:.2f}'

def check_balance(self):
    print(self.balance)

def deposit(self, dep_num):
    self.balance += dep_num

def withdraw(self, wd_num):
    if self.balance + self.limit >= wd_num:
        self.balance -= wd_num
    else:
        return 'Your balance is insufficient'

def add_interest(self):
    self.balance *= (1 + (self.interest / 100))

class Credit(Account):
def __init__(self, withdrawl_rate=5):
    self.wth_rate = withdrawl_rate
    super().__init__(self)
    # super().__init__(self, open_deposit, overdraft_limit, interest_rate)

def __str__(self):
    return f'Credit Account: # {self.number} \nBalance: {Account.__str__(self)}'

def withdraw(self, wd_num):
    total_amount = wd_num * (1 + (self.wth_rate / 100))
    Account.withdraw(self, total_amount)

def change_limit(self, limit):
    self.limit = limit


x = Credit()
x.number
Out[]: <__main__.Credit at 0x109c13250>

其他属性效果很好:

x.wth_rate
Out[]: 5
x.balance
Out[]: 100
x.add_interest()
x.balance
Out[]: 101.0

标签: pythonclass

解决方案


如果默认情况下已经获取的基类与其他实例函数一样,则您将传递self给该函数。__init__self

所以self你传递的是基类的第一个参数init,也就是acct_num,所以它只包含一个指向实例的指针。

例如,您需要调用super().__init__(acct_num=SOME_VALUE)以获得所需的行为。


推荐阅读