Reputation: 8317
I am a little confused by the object model of Python. I have two classes, one inherits from the other.
class Node():
def __init__(identifier):
self.identifier = identifier
class Atom(Node):
def __init__(symbol)
self.symbol = symbol
What I am trying to do is not to override the __init__() method, but to create an instance of atom that will have attributes symbol and identifier.
Like this:
Atom("Fe", 1) # will create an atom with symbol "Fe" and identifier "1"
Thus I want to be able to access Atom.identifier and Atom.symbol once an instance of Atom is created.
How can I do that?
Upvotes: 8
Views: 547
Reputation: 76788
You have to call the __init__
-method of the super-class manually.
class Atom(Node):
def __init__(self, symbol, identifier)
Node.__init__(self, identifier)
self.symbol = symbol
Upvotes: 6
Reputation: 12700
>>> class Node(object):
... def __init__(self, id_):
... self.id_ = id_
...
>>> class Atom(Node):
... def __init__(self, symbol, id_):
... super(Atom, self).__init__(id_)
... self.symbol = symbol
...
>>> a = Atom("FE", 1)
>>> a.symbol
'FE'
>>> a.id_
1
>>> type(a)
<class '__main__.Atom'>
>>>
It's a good idea to inherit from object in your code.
Upvotes: 7
Reputation: 4879
class Node():
def __init__(self, identifier):
self.identifier = identifier
class Atom(Node):
def __init__(self, symbol, *args, **kwargs)
super(Atom, self).__init__(*args, **kwargs)
self.symbol = symbol
See here for an explanation of the *args
and **kwargs
. By using super
, you can access the base class (superclass) of the Atom class and call it's __init__
. Also, the self
parameter needs to be included as well.
Upvotes: 1
Reputation: 2738
When creating a class you need to use the self word in the declaration. After that you can define the other arguments. To inherit call the super init method:
>>> class Node():
... def __init__(self, identifier):
... self.identifier = identifier
...
>>>
>>> class Atom(Node):
... def __init__(self, symbol, identifier):
... Node.__init__(self, identifier)
... self.symbol = symbol
...
>>>
>>>
>>> fe = Atom("Fe", 1)
>>> fe.symbol
'Fe'
>>> fe.identifier
1
>>>
Upvotes: 3
Reputation: 50941
class Node(object):
def __init__(self, identifier):
self.identifier = identifier
class Atom(Node):
def __init__(self, symbol, *args, **kwargs)
super(Atom, self).__init__(*args, **kwargs)
self.symbol = symbol
Points:
object
.super
to call parent classes' __init__
functions.self
as the first parameter in Python.Upvotes: 1
Reputation: 36504
You have two missing things in your code:
methods belonging to a class have to have an explicit self
parameter, which you are missing
Your derived 'Atom' class also needs to accept the parameter it needs to use to initialize the base class.
Something more like:
class Node():
def __init__(self, identifier):
self.identifier = identifier
class Atom(Node):
def __init__(self, identifier, symbol)
Node.__init__(self, identifier)
self.symbol = symbol
Upvotes: 2