类不带参数(给定1个) [英] Class takes no arguments (1 given)

查看:39
本文介绍了类不带参数(给定1个)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class MyClass:
    def say():
        print("hello")

mc = MyClass()
mc.say()

我遇到错误: TypeError:say()不接受任何参数(给定1个).我在做什么错了?

I am getting error: TypeError: say() takes no arguments (1 given). What I am doing wrong?

推荐答案

这是因为类中的方法期望第一个参数是 self .该 self 参数由python内部传递,因为它在调用方法时始终向其自身发送引用,即使该方法未在其中使用

This is because methods in a class expect the first argument to be self. This self parameter is passed internally by python as it always sends a reference to itself when calling a method, even if it's unused within the method

class MyClass:
    def say(self):
        print("hello")

mc = MyClass()
mc.say()
>> hello

或者,您可以将方法设为静态并删除 self 参数

Alternatively, you can make the method static and remove the self parameter

class MyClass:
    @staticmethod
    def say():
        print("hello")

mc = MyClass()
mc.say()
>> hello

这篇关于类不带参数(给定1个)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆