【问题标题】:Self referencing variables passed during the instantiation of a class在类的实例化期间传递的自引用变量
【发布时间】:2016-11-01 20:51:31
【问题描述】:

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

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_indexecon_index 的初始值是什么,但这不是我目前的设置方式是不允许的。是否有另一种方法可以在创建此类时动态设置关键字变量?

【问题讨论】:

  • 默认值是在定义时(类块执行时)确定的,而不是在函数运行时确定的,只需将确定其值的代码放在函数体中即可。
  • 请注意,这就是拥有__init__ 方法的全部意义,它可以运行一些代码来创建对象。您的 age 将始终默认为在定义时仅生成一次的相同数字,而不是每个实例生成一次。
  • 所以你是说如果我分别实例化 2 类,年龄值将始终相同?有什么办法可以让每个实例化的随机年龄?
  • 您会注意到,在我的回答中,age 默认为None,并在函数体中初始化为随机数。这就是每次运行函数时设置值的方式,在函数体中进行。

标签: python class scope instantiation


【解决方案1】:

假设您希望 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

【讨论】:

  • 我明白了,这似乎是我试图实现的更好的实现。我确实希望 social_indexecon_index 是可选参数,它们将覆盖任何确定默认值的逻辑,因此您的第一个示例正是我想要的。谢谢!
猜你喜欢
  • 1970-01-01
  • 2018-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-15
  • 1970-01-01
相关资源
最近更新 更多