Reputation: 12535
I have a class C. I would like to instantiate this class with one argument. Let's call that argument d. So I would like to do myC = C(d=5). C should also have another variable called e. e's value should be set to d on instantiation of the class.
So I wrote this:
>>> class C:
... def __init__(self,d):
... self.d = d
... e = d
...
But that gives me the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in C
NameError: name 'd' is not defined
Ok fine, So I will try something slightly different:
>>> class C:
... def __init__(self,d):
... self.d = d
... e = self.d
...
But that gives me this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in C
NameError: name 'self' is not defined
So how should I do what I'm trying to do?? This should be very simple.
Upvotes: 1
Views: 129
Reputation: 1121406
You need to make e
part of the __init__
method as well. d
is not defined until that function is called:
class C:
def __init__(self,d):
self.d = d
self.e = d
You can put these on the same line if you want to:
class C:
def __init__(self,d):
self.d = self.e = d
If you need e
to be a class attribute instead of an instance attribute, refer directly to the class:
class C:
def __init__(self,d):
self.d = d
C.e = d
or use type(self)
:
class C:
def __init__(self,d):
self.d = d
type(self).e = d
The latter means that if you subclass C
, the class attribute will be set on the appropriate subclass instead.
Upvotes: 8