2013-06-01 37 views
1

我有一个类C. 我想用一个参数实例化这个类。我们称之为参数d。 所以我想做myC = C(d = 5)。 C还应该有另一个变量叫做e。 e的值应该设置为d在实例化类上。Python:如何根据__init __()参数设置类变量?

所以我写了这一点:

>>> class C: 
...  def __init__(self,d): 
...   self.d = d 
...  e = d 
... 

但是,这使我有以下错误:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 4, in C 
NameError: name 'd' is not defined 

那么好吧,所以我会尝试一些稍有不同:

>>> class C: 
...  def __init__(self,d): 
...   self.d = d 
...  e = self.d 
... 

但这给了我这个错误:

Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 4, in C 
NameError: name 'self' is not defined 

那么我该怎么做我想做的?这应该很简单。

回答

0
class C: 
    def __init__(self,d): 
     self.d = self.e = d 
8

你需要做__init__方法e一部分。 d没有定义,直到调用该函数:

class C: 
    def __init__(self,d): 
     self.d = d 
     self.e = d 

你可以把这些放在同一行,如果你想:

class C: 
    def __init__(self,d): 
     self.d = self.e = d 

如果您需要e是一个类属性而不是实例属性,直接引用类:

class C: 
    def __init__(self,d): 
     self.d = d 
     C.e = d 

,或者使用type(self)

class C: 
    def __init__(self,d): 
     self.d = d 
     type(self).e = d 

后者意味着如果你继承了C,那么类属性将被设置在适当的子类上。

相关问题