Discuss / Python / 学习补充大神的想法:

学习补充大神的想法:

Topic source

钱老板boss

#1 Created at ... [Delete] [Delete and Lock User]
  • class compute(object): def init(self,x,y):
     self.x = x
     self.y = y
    
    def add(self,x,y):
     return self.x + self.y
    
    def sub(self,x,y):
     return self.x - self.y
    
    def mul(self,x,y):
     return self.x * self.y
    
    def div(self,x,y):
     if y != 0:
         return self.x / self.y
     else:
         raise  ValueError('y can not be zero')
    
    #假设还有上百种计算的公式,此命名为getAttr3_29.py

另外一个文件为3_29testGetAttr.py文件 代码为:

  • from getAttr3_29 import compute #模块的命名不能以数字开头

def run(x,y): compute_type = compute(x, y) inp = input('请输入需要计算的方法:')

#判断是否有这个属性
if hasattr(compute_type,inp):
#有这个属性,则获取然后赋值给新的变量
    fun_temp = getattr(compute_type,inp)
    print(fun_temp(x,y))
else:
    #如果没有则set方法,求两个数的平方和
    setattr(compute_type,inp,lambda x,y:x*x+y*y)
    func_temp2 = getattr(compute_type,inp)
    print(func_temp2(x,y))

if name == 'main': m = int(input('请输入一个数:')) n = int(input('请再次输入一个数:')) run(m,n)


  • 1

Reply