理解 Python 中的对象
我对 Python 的对象模型有点困惑。我有两个类,一个类继承另一个类。
class Node():
def __init__(identifier):
self.identifier = identifier
class Atom(Node):
def __init__(symbol)
self.symbol = symbol
我想做的不是重写 __init__() 方法,而是创建一个具有属性 symbol 的atom实例> 和标识符。
像这样:
Atom("Fe", 1) # will create an atom with symbol "Fe" and identifier "1"
因此,我希望在创建 Atom 实例后能够访问 Atom.identifier 和 Atom.symbol。
我怎样才能做到这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在代码中从对象继承是个好主意。
It's a good idea to inherit from object in your code.
您必须手动调用超类的 __init__ 方法。
You have to call the
__init__
-method of the super-class manually.创建类时,您需要在声明中使用 self 词。之后您可以定义其他参数。要继承,请调用超级 init 方法:
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:
您的代码中缺少两个内容:
属于类的方法必须具有显式的
self
参数,而您缺少该参数您的派生“Atom”类还需要接受用于初始化基类的参数。
更像是:
You have two missing things in your code:
methods belonging to a class have to have an explicit
self
parameter, which you are missingYour derived 'Atom' class also needs to accept the parameter it needs to use to initialize the base class.
Something more like:
要点:
object
。super
调用父类的__init__
函数。Points:
object
.super
to call parent classes'__init__
functions.self
as the first parameter in Python.有关
*args< 的说明,请参阅此处 /code> 和
**kwargs
。通过使用super
可以访问基类Atom 类的(超类)并将其命名为__init__
。此外,还需要包含self
参数。See here for an explanation of the
*args
and**kwargs
. By usingsuper
, you can access the base class (superclass) of the Atom class and call it's__init__
. Also, theself
parameter needs to be included as well.