在类的实例化期间传递的自引用变量

时间:2016-06-29 23:15:35

标签: python class scope instantiation

我不确定我是否使用了正确的术语,但这是我的代码:

class Candidate(object):
        def __init__(self, party_code, state, age=random.randint(35, 70),
                social_index=(1 if party_code == 'dem' else -1 if party_code == 'rep' else 0),
                econ_index=(-1 if party_code == 'dem' else 1 if party_code == 'rep' else 0)):
            self.state = state
            self.party_code = party_code
            self.age = age
            self.social_index = social_index
            self.econ_index = econ_index

我希望能够使用 party_code 来确定 social_index econ_index 的初始值,但这不是&# 39; t允许我现在设置的方式。是否有另一种方法可以在创建此类时动态设置关键字变量?

1 个答案:

答案 0 :(得分:0)

假设您希望social_indexecon_index成为您的代码的参数:

class Candidate(object):
    def __init__(self, party_code, state, age=None,
            social_index=None, econ_index=None):
        if age is None:
            age=random.randint(35, 70)
        if social_index is None:
            social_index = (1 if party_code == 'dem' else -1 if party_code == 'rep' else 0)
        if econ_index is None:
            econ_index=(-1 if party_code == 'dem' else 1 if party_code == 'rep' else 0)
        self.state = state
        self.party_code = party_code
        self.age = age
        self.social_index = social_index
        self.econ_index = econ_index

您需要指定逻辑来确定函数体中的值,以便在调用函数时执行它。函数的默认值是根据定义(def块)确定的,这就是Mutable default trap存在的原因。

另一方面,如果您不需要将它们作为参数传递,您可以将其简化为:

class Candidate(object):
    def __init__(self, party_code, state):
        self.state = state
        self.party_code = party_code
        self.age = random.randint(35, 70)
        if party_code == 'dem':
            self.social_index = 1
            self.econ_index = -1
        elif party_code == "rep":
            self.social_index = 0
            self.econ_index = 0
        else:
            self.social_index = 0
            self.econ_index = 0