繁体   English   中英

我做错了什么,缺少 1 个必需的位置参数:'self'

[英]what did i do wrong missing 1 required positional argument: 'self'

class Area(object): def __init__(self, base, height): self.base = base self.height = height def calculation(self): return(self.base * self.height) area = Area(15, 2) print(Area.calculation())

print()中的Area是大写的,而您的可变area不是。 这意味着您正在调用区域 Object 而不是变量。
这应该工作:

class Area(object):
    def __init__(self, base, height):
        self.base = base
        self.height = height

    def calculation(self):
        return(self.base * self.height)

area = Area(15, 2)
print(area.calculation())

您正在调用 class 对象的calculation方法 ( Area.calculation ),而不是调用Area实例calculation方法 ( area.calculation )。 这有效:

class Area(object):
    def __init__(self, base, height):
        self.base = base
        self.height = height

    def calculation(self):
        return self.base * self.height

area = Area(15, 2)
print(area.calculation())

请注意return参数周围删除的括号 - 它们是不必要的,因为return是关键字,而不是 function。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM