Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding objects in Python

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?

like image 709
Tomas Novotny Avatar asked Nov 05 '10 16:11

Tomas Novotny


1 Answers

>>> 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.

like image 134
aeter Avatar answered Sep 21 '22 00:09

aeter