Python - 重写功能代码的更好方法?

时间:2018-05-08 08:36:48

标签: python

使用全局变量很容易呈现整个设计。但是全局变量有一些约束。它不能像整个班级一样运作。

最好在代码中编写一个选择函数。

在课堂上将是明智选择。

现在选择变量在类之外。

将代码重写到类中。

输出

 Enter choice: 1 for full_name, 2 for age, 3 for bmi, 4 for analysis
 user enter 1 
 output: Alex L. 
 user enter 2 
 output:28 
 user enter 3
 ouput:0.0024691358024691358 
 user enter 4 
 output:You need to eat more.

不要使用全局变量并使用“def choice:”来重写它。

import datetime

choice=input('Enter choice: 1 for full_name, 2 for age, 3 for bmi, 4 for analysis')
choice=int(choice)
class Person:
  def __init__(self, name, birthday_year, address, telephone, email):
      self.name = name
      self.birthday_year = birthday_year
      self.address= address
      self.telephone = telephone
      self.email = email

  def full_name(self,surname,firstname):
      self.surname = surname
      self.firstname = firstname
      return self.firstname+" "+self.surname

  def age(self,birthday_year):
      self.birthday_year=birthday_year
      currentyear= datetime.datetime.now().year
      age = currentyear - self.birthday_year
      return age

  def bmi(self,weight,height):
      self.weight= weight
      self.height = height
      result= self.weight / (self.height**2)
      return result

  def analysis(self,result):
      self.result=result
      if result < 18.5:
         print ("You need to eat more.")
      elif result > 25:
         print ("Try to care yourself.")
      else:
         print ("You are a healthy person.")


def main():

    s= Person ("Alex",1990,"Wonderland",2345678,"aa@smail.com")
    if choice== 1:
       a = s.full_name("L.", "Alex")
       print(a)
    elif choice==2:
       b = s.age(1990)
       print(b)
    elif choice==3:
       c = s.bmi(80, 180)
       print(c)
    elif choice ==4:
       c = s.bmi(80, 180)
       d = s.analysis(c)
       print(d)
    else:
       print("invaild entry")

if __name__ == "__main__":
    main()

1 个答案:

答案 0 :(得分:1)

您可以使用需要在每个选择中运行的字典和函数。这是一个示例代码。您需要修改此代码以满足您的需求。

def one():
    return "Alex L"


def two():
    return "28"


def three():
    return "0.0024691358024691358"


def four():
    return "You need to eat more"


def choice(argument):
    switcher = {
        1: one,
        2: two,
        3: three,
        4: four,
    }
# Get the function from switcher dictionary
    func = switcher.get(argument, lambda: "Invalid choice")
# Execute the function
    print(func())


choice(1)
choice(2)
choice(3)
choice(4)