在Python中进行练习时,我试图将变量传递给类的对象,并且该变量具有类的函数名称,但出现错误,没有出现跟随错误...
class testing():
def __init__(self, name):
print('This is From INIT of testing calss...')
self.name = name
def good(self):
print('Hello {} Good things of the day'.format(self.name))
def bad(self):
print('Hello {} Bad things of the day'.format(self.name))
ts = testing('Pranit')
ch = str(input('Enter choice : good or bad :'))
ts.ch()
output error
C:\Users\pranit>python "C:\Users\pranit\Music\Python Only\FunPractice.py"
This is From INIT of testing calss...
Enter choice : good or bad :good
Traceback (most recent call last):
File "C:\Users\pranit\Music\Python Only\FunPractice.py", line 15, in <module>
ts.ch()
AttributeError: 'testing' object has no attribute 'ch'
C:\Users\pranit>
答案 0 :(得分:1)
通常,解决方案是getattr(obj, name[, default=None)
:
ts = testing('Pranit')
ch = input('Enter choice : good or bad :')
method = getattr(ts, ch, None)
if method:
method()
但是在这种情况下(基于用户输入选择函数或方法)(出于安全原因)最好在客户端代码中明确映射允许的函数/方法:
ts = testing('Pranit')
allowed = {"good": ts.good, "bad": ts.bad}
ch = input('Enter choice : good or bad :')
method = allowed.get(ch, None)
if method:
method()
或直接在类中(取决于谁负责了解此处允许使用哪些方法):
# XXX Python naming conventions: class names should be CamelCased
class Testing():
def __init__(self, name):
print('This is From INIT of testing calss...')
self.name = name
def good(self):
print('Hello {} Good things of the day'.format(self.name))
def bad(self):
print('Hello {} Bad things of the day'.format(self.name))
ALLOWED = {"good": good, "bad": bad}
def handle(self, choice):
if choice not in self.ALLOWED:
raise ValueError("'%s' is not a valid choice" % choice)
return self.ALLOWED[choice][self]
答案 1 :(得分:-1)
您的课程只有一个属性:name
和2个方法good()
和bad()
。因此,当您调用ts.ch()
时会收到错误消息,因为您正在调用的方法ch()
不存在。
您应该使用参数来定义方法的优缺点:
class testing():
def __init__(self, name):
print('This is From INIT of testing calss...')
self.name = name
def good(self):
print('Hello {} Good things of the day'.format(self.name))
def bad(self):
print('Hello {} Bad things of the day'.format(self.name))
def good_or_bad(self, param):
# Param is either good or bad
if param.lower() == "good":
self.good()
else:
self.bad()
然后将ts.ch()
替换为ts.good_or_bad(ch)
。