理解Python中的对象

Tom*_*tny 7 python object object-model

我对Python的对象模型有点困惑.我有两个类,一个继承自另一个.

class Node():
  def __init__(identifier):
    self.identifier = identifier

class Atom(Node):
  def __init__(symbol)
    self.symbol = symbol
Run Code Online (Sandbox Code Playgroud)

我要做的是不要覆盖__ init __()方法,而是创建一个具有属性symbolidentifier的atom实例.

像这样:

Atom("Fe", 1) # will create an atom with symbol "Fe" and identifier "1"
Run Code Online (Sandbox Code Playgroud)

因此,我希望能够在创建Atom实例后访问Atom.identifier和Atom.symbol.

我怎样才能做到这一点?

aet*_*ter 7

>>> 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'>
>>> 
Run Code Online (Sandbox Code Playgroud)

在代码中继承对象是个好主意.


Bjö*_*lex 6

你必须__init__手动调用超类的-method.

class Atom(Node):
  def __init__(self, symbol, identifier)
    Node.__init__(self, identifier)
    self.symbol = symbol
Run Code Online (Sandbox Code Playgroud)