Discuss / Python / 求助一下大家

求助一下大家

Topic source

随机清醒

#1 Created at ... [Delete] [Delete and Lock User]

关于楼上那位大神贴的代码: 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()) 基础很差,希望得到大家的解答,先谢谢了

随机清醒

#2 Created at ... [Delete] [Delete and Lock User]

说错了,computer是实例

随机清醒

#3 Created at ... [Delete] [Delete and Lock User]

改成print(computer.inp()) 报错 'MyObject' object has no attribute 'inp'

飞鸟变龙

#4 Created at ... [Delete] [Delete and Lock User]

我的理解是getattr(computer,inp)是取内存指针(指向方法),而你input得到的只是个指向你输入的字符串的指针。所以,你可以用getattr(computer,inp)().

暗影之_刃

#5 Created at ... [Delete] [Delete and Lock User]

个人理解:你下边的inp只是一个字符串,而上边的是指向该方法的一个地址


  • 1

Reply