Discuss / Python / homework

homework

Topic source

Mr_RightMen

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

看到评论中有同学在问,这一章所讲的内容一般在什么时候会用到呢,我就翻了下,然后记录下来,给后面的同学做个参考。

# 首先你有一个command.py文件,内容如下,这里我们假若它后面还有100个方法

class MyObject(object):
    def __init__(self):
        self.x = 9
    def add(self):
        return self.x + self.x

    def pow(self):
        return self.x * self.x

    def sub(self):
        return self.x - self.x

    def div(self):
        return self.x / self.x
# 然后我们有一个入口文件 exec.py,要根据用户的输入来执行后端的操作
from command import MyObject
computer=MyObject()

def run():
    inp = input('method>')

    if inp == 'add':
        computer.add()
    elif inp == 'sub':
        computer.sub()
    elif inp == 'div':
        computer.div()
    elif inp == 'pow':
        computer.pow()
    else:
        print('404')

上面使用了if来进行判断,那么假若我的command里面真的有100个方法,那我总不可能写100次判断吧,所以这里我们就会用到python的反射特性,看下面的代码

from command import MyObject

computer=MyObject()
def run(x):
    inp = input('method>')
    # 判断是否有这个属性
    if hasattr(computer,inp):
    # 有就获取然后赋值给新的变量
        func = getattr(computer,inp)
        print(func())
    else:
    # 没有我们来set一个
        setattr(computer,inp,lambda x:x+1)
        func = getattr(computer,inp)
        print(func(x))

if __name__ == '__main__':
    run(10)

其实本章的内容,很多涉及到动态加载模块类,不知道为什么老师没讲,我也不知道自己说的对不对。

学习了

学习了

郝仁E哥

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

不错哦!

毛思懿Y

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

run(a)

method add 18

run(a)

method add1

因为没有add1这个属性,应该set一个,但为什么会报错呢?

非常感谢

请问为什么会出先No module named 'command'的错误

讲得很好,非常感谢


Reply