Python实例变量赋值标准编程实践

时间:2019-01-30 06:48:29

标签: python python-3.x

我必须定义实例变量,可以通过不同的实例方法访问该实例变量。因此,我在构造函数下设置实例变量。我看到在构造函数下初始化实例变量的效果最好。

在构造函数下使用if else条件定义实例变量是一种好的做法。在标准编码实践中是否还有其他Python方式可实现此目的。

class Test:
    def __init__(self, EmpName, Team):
        self.EmpName = EmpName
        self.Team = Team
        if Team == "Dev":
            self.Manager = "Bob"
        elif Team == "QA":
            self.Manager = "Kim"
        elif Team == "Admin":
            self.Manager == "Jeff" 

4 个答案:

答案 0 :(得分:2)

团队与经理之间的关系是非常直接的数据;我不想将其作为代码。因此,查找字典将是我的选择。

class Test:
    TEAM_MANAGERS = {
        "Dev": "Bob",
        "QA": "Kim",
        "Admin": "Jeff",
    }

    def __init__(self, emp_name, team):
        self.emp_name = emp_name
        self.team = team
        try:
            self.manager = TEAM_MANAGERS[team]
        except KeyError:
            raise ArgumentError("Unknown team")

答案 1 :(得分:1)

对于面向对象的编程,通常将这样的数据和结构混合在一起是非常糟糕的编码实践,Python也不例外。有很多方法可以解决这个问题:

  • 您可以将团队经理传给其他人;但看来这是您要自动化的步骤
  • 您可以将Employee链接到团队实例,例如:

类似的东西:

class Team:
    def __init__(self, name, manager):
        self.name = name
        self.manager = manager


class Employee:
    def __init__(self, name, team):
        self.name = name
        self.team = team


team_dev = Team("Dev", "Bob")
team_qa = Team("QA", "Kim")
employee_1 = Employee("Jack", team_dev)

print(f'{employee_1.name} is on {employee_1.team.name} as managed by {employee_1.team.manager}')

请注意,变量不应为CamelCase,而应为类名。

一个更好的解决方案可能是让团队的经理自己成为雇员。当然,那么在创建员工时需要团队,而在创建团队时需要员工,因此最初可能需要为无:

class Team:
    def __init__(self, name, manager=None):
        self.name = name
        self.manager = manager


class Employee:
    def __init__(self, name, team):
        self.name = name
        self.team = team


team_dev = Team("Dev")
team_dev.manager = Employee("Bob", team_dev)
team_qa = Team("QA")
team_qa.manager = Employee("Kim", team_qa)
employee_1 = Employee("Jack", team_dev)

print(f'{employee_1.name} is on {employee_1.team.name} as managed by {employee_1.team.manager.name}')

答案 2 :(得分:0)

if-else方法内使用__init__()并没有错。 根据您要初始化特定变量的条件,这是适当的。

答案 3 :(得分:0)

class Test():
    def __init__(self,EmpName = "",Team = ""):
        self.EmpName = EmpName
        self.Team = Team
        self.Manager = Manager
        if self.Team == "Dev":
            self.Manager = "Bob"
        elif self.Team == "Dev":
            self.Manager = "Kim"
        elif self.Team == "Admin":
            self.manager = "Jeff"
        else:
            self.manager = ""
    def get_manager(self):
        return self.Manager

obj = Test("DemoEmp","Dev")
print (obj.get_manager())