【问题标题】:How to accept an object in a __init__ statement of another?如何在另一个的 __init__ 语句中接受一个对象?
【发布时间】:2016-03-20 17:04:08
【问题描述】:

我正在尝试制作一个 Pokemon 模拟器,并且我正在尝试将一个 Type 对象传递给我的 Move 对象,但我不明白如何传递它。

class Type:
    def __init__(self):
        self.name="fire"
        self.atNOR=1
        self.atFIG=1
        self.atFLY=1
        self.atPOS=1
        self.atGRO=1
        self.atROC=1
        self.atBUG=1
        self.atGHO=1
        self.atFIR=1
        self.atWAT=1
        self.atGRA=1
        self.atELE=1
        self.atPSY=1
        self.atICE=1
        self.atDRA=1
class Move:
    def __init__(self):
        self.name = "tackle"
        self.power= 0
        self.ability= "none"
        self.type= normal

这只是告诉我 normal 不是数据类型,我不知道如何让这一行将这个 normal 变量定义为 Type

【问题讨论】:

  • normal 到底是什么?您能否将其定义包含在代码 sn-p 中?
  • 其实在python中,对象的类型就是对象本身。现在您希望在self.type 中添加什么?
  • normal 应该是 Move 对象的默认类型。
  • @Kasramvd 我想在 self.type 中放入一个 Type 对象
  • @Dad 你没有将normal 传递给你的构造函数,也没有在任何地方定义它,所以它会引发NameError。如果你想在你的类的属性上设置一个类型对象或任何东西,你需要在之前定义它或传递给你的__init__

标签: python oop python-3.x object


【解决方案1】:

如果您想在 Move 对象中拥有“Type”对象作为属性,则需要使用“composition pattern”(因此 Move has-a Type):

class Move:
    def __init__(self):
        self.name = "tackle"
        self.power = 0
        self.ability = "none"
        self.type = Type()

更多关于组合/继承here

LearnPythonTheHardway 并不总是学习 Python 的好资源,但实际上在这个主题中相当不错。

使用“类型”作为类名时要小心。小写type 实际上是内置的 Python 类,可以用作元类编程(或一般创建类)的构造。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多