python - 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
解决方案
如果默认情况下已经获取的基类与其他实例函数一样,则您将传递self
给该函数。__init__
self
所以self
你传递的是基类的第一个参数init
,也就是acct_num
,所以它只包含一个指向实例的指针。
例如,您需要调用super().__init__(acct_num=SOME_VALUE)
以获得所需的行为。
推荐阅读
- python - 为什么某些 Django 类和默认应用程序被称为 API?
- typescript - 计算给定边界框和检测到的字符的近似文本行高
- python - 在带有 Buster 64 位操作系统的 Raspberry pi 3B+ 上运行 Selenium 的问题
- reactjs - 内容安全策略:在节点包中面临内联样式问题
- javascript - 使用 Javascript 计算表中的条目
- function - 如何将用户输入与python中现有文件中的数据相匹配?
- c# - 如何通过 UI 自动化获取 PowerPoint 标题?
- qt - QT 属性警告,因为属性没有只读写入
- api - 如何从 API 请求数据
- vue.js - 使用 vuejs 查找未打折的价格