我在类中定义了一个main函数,以及一个使用def __str__(self):方法返回对象属性的方法。既然我在类中调用__repr__,这是否是调用该函数的正确方式?另外,是否有一个更好的选择,必须使用一个长链的if,elif,和其他的呢?
代码:
def main(self):
"""Create usability of the account. Accessing the account
should enable the user to check the account balance, make
a deposit, and make a withdrawal."""
main_menu = {1: 'Balance', 2: 'Deposit', 3: 'Withdraw', 4: 'Exit'}
using_account = True
while using_account:
print '\nAvailable Choices:'
print '\n'.join('%d.) %s' % (i, choice) for i, choice in
main_menu.iteritems())
my_choice = int(raw_input('Enter a choice: '))
if my_choice == 1:
self.current_balance()
elif my_choice == 2:
self.deposit_funds()
elif my_choice == 3:
self.withdraw_funds()
elif my_choice == 4:
print self.__repr__()
using_account = False
else:
print 'Invalid choice, try again!'发布于 2013-11-30 22:23:06
在调用some_object.__repr__() (无论是显式还是隐式)时调用repr(some_object)。直接调用它是可以的,但是大多数人都会写repr(self)。
至于if语句链,它还不够混乱,还不足以让人担心;-)另一种选择:
int2meth = {1: "current_balance", 2: "deposit_funds",
3: "withdraw_funds", 4: "__repr__"}您可以将该数据集存储在任何地方(模块级、类级、.)。
然后
methname = int2meth.get(my_choice)
if methname is None:
print 'Invalid choice, try again!'
else:
getattr(self, methname)()当然,类似的事情可以用一个列表来做,而不是一个小块。丁提供了另一种可能性:使用字符串作为键,而不是无意义的小整数。
发布于 2013-11-30 22:28:13
..。elif my_choice == 4:打印self.__repr__() .
如果你这样做会发生什么:打印(自我)
发布于 2013-11-30 22:30:06
与所有__magic__方法一样,__repr__应该通过操作符或类似于内置函数的运算符来调用,在这种情况下,可以使用repr()或℅r格式说明符。
https://stackoverflow.com/questions/20306226
复制相似问题