我在练习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发布于 2020-11-27 11:22:36
如果基类与其他实例函数一样,在默认情况下已经获得self,则将__init__函数传递给__init__函数。
因此,您要传递的self是基类init的第一个参数,即acct_num,因此它将只提供一个指向实例的指针。
例如,您需要调用super().__init__(acct_num=SOME_VALUE)来获得所需的行为。
https://stackoverflow.com/questions/65036391
复制相似问题