关于楼上那位大神贴的代码: conputer是一个类,x是一个实例
def run(x): inp = input('method>') if hasattr(computer,inp): func = getattr(computer,inp) print(func()) 这个地方为什么要定义一个func,像下面一样直接输出inp方法为什么不行
def run(x): inp = input('method>') if hasattr(computer,inp): print(inp()) 基础很差,希望得到大家的解答,先谢谢了
说错了,computer是实例
改成print(computer.inp()) 报错 'MyObject' object has no attribute 'inp'
我的理解是getattr(computer,inp)是取内存指针(指向方法),而你input得到的只是个指向你输入的字符串的指针。所以,你可以用getattr(computer,inp)().
个人理解:你下边的inp只是一个字符串,而上边的是指向该方法的一个地址
Sign in to make a reply
随机清醒
关于楼上那位大神贴的代码: conputer是一个类,x是一个实例
def run(x): inp = input('method>') if hasattr(computer,inp): func = getattr(computer,inp) print(func()) 这个地方为什么要定义一个func,像下面一样直接输出inp方法为什么不行
def run(x): inp = input('method>') if hasattr(computer,inp): print(inp()) 基础很差,希望得到大家的解答,先谢谢了