【问题标题】:'str' object not callable error How do I make my classes overload?“str”对象不可调用错误如何使我的类重载?
【发布时间】:2021-02-06 22:07:51
【问题描述】:

我试图在我制作的这个类中重载我的运算符。我做了这个植物课,我正在尝试把它打印出来。我对此仍然很陌生,所以我的理解可能不是最好的,但是您可以提供的任何帮助都会很棒。这是我的 mmain.py:

import Fungi_
import Animal
import inheritance
import Monera
import Plant

grass = Plant.Ferns("Good", "large")
print(grass.scent() + grass.size())

这是我的类和子类,

from inheritance_assignment import living_thing

class Plant(living_thing):
    def __init__(self, type):
        self.type = type

class Equiseta(Plant):
    def __init__(self, type, color):
        self.type = type
        self.color = color

class Lycopodia(Plant):
    def __init__(self, color, size):
        self.color = color
        self.size = size

class Gymnosperms(Plant):
    def __init__(self, size, color):
        self.size = size
        self.color = color

class Anginosperm(Plant):
    def __init__(self, length, color):
        self.length = length
        self.color = color

class Ferns(Plant):
    def __init__(self, scent, size):
        self.scent = scent
        self.size = size

class Mosses(Plant):
    def __init__(self, wetness, size):
        self.wetness = wetness
        self.size = size

这是它给我的错误

Traceback (most recent call last):
  File "main.py", line 8, in <module>
    print(grass.scent() + grass.size())
TypeError: 'str' object is not callable

任何信息都将是盛大的!提前致谢。

【问题讨论】:

  • 错误信息很清楚。你为什么要打电话给grass.scentgrass.size

标签: python inheritance overloading


【解决方案1】:

python 中的类有方法(函数)和属性(变量)。在您的Ferns 类中,您将sizescent 定义为属性,但是您试图在print 语句中访问它们,就好像它们是通过将() 附加到它们的名称的方法一样。假设您想要连接与 scentsize 关联的字符串,那么这个语法应该可以工作:

print(grass.scent + grass.size)
Goodlarge

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    相关资源
    最近更新 更多