【问题标题】:Getting an error: object() takes no parameters in Python [closed]出现错误:object() 在 Python 中没有参数 [关闭]
【发布时间】:2021-05-10 22:57:07
【问题描述】:

我收到 TypeErrorobjects 没有参数

我不知道我的代码有什么问题。谁能帮我弄清楚。

class Animal:

    def _init_(self, color):
        self.color = color
    
bingo = Animal("Brown")

print(bingo.color)

【问题讨论】:

  • __init__周围需要双下划线
  • 我有多傻?非常感谢,

标签: python class methods constructor instance


【解决方案1】:

您正在考虑将_init_ 方法作为Animal 类的构造函数。但是,您需要在构造函数(如this)之前和之后放置双下划线。以下代码工作正常:

class Animal:
    def __init__(self, color):
        self.color = color

bingo = Animal("Brown")
print(bingo.color)

如果您不想更改 _init_ 方法的名称,则需要像这样以不同的方式调用它:

class Animal:
    def _init_(self, color):
        self.color = color

bingo = Animal()
bingo._init_("Brown");
print(bingo.color)

这也应该可以正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-17
    • 2021-02-21
    • 2019-01-31
    • 1970-01-01
    • 2022-09-24
    • 2018-02-26
    相关资源
    最近更新 更多