Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 调用类实例方法不';不要打印任何东西_Python_Class_Inheritance_Instantiation - Fatal编程技术网

Python 调用类实例方法不';不要打印任何东西

Python 调用类实例方法不';不要打印任何东西,python,class,inheritance,instantiation,Python,Class,Inheritance,Instantiation,问题: 为什么m1.greeting()不起作用 重新措辞:为什么m1.greeting()不打印(我的数据)?您需要通过self class mainClass: def greeting(): mydata = input('How are you?') print(mydata) m1 = mainClass() m1.greeting() 或者声明问候语aclassmethod def greeting(self): mydata =

问题: 为什么
m1.greeting()
不起作用


重新措辞:为什么
m1.greeting()
不打印(我的数据)?

您需要通过
self

class mainClass:

    def greeting():
        mydata = input('How are you?')
        print(mydata)

m1 = mainClass()
m1.greeting()
或者声明
问候语
a
classmethod

def greeting(self):
    mydata = input('How are you?')
    print(mydata)

除非有更多的后续内容,否则这里没有真正的理由引入OOP,
问候语
可能只是一个免费函数。

您可以在创建函数时声明一个
self
参数,或者使用
@staticmethod
@classmethod
cls
参数。在下面检查它们。您可以阅读这些差异

创建函数时声明
自身
参数

@classmethod
def greeting():
    mydata = input('How are you?')
    print(mydata)
class mainClass:
    def greeting(self):
        mydata = input('How are you? ')
        print(mydata)
@staticmethod
def greeting():
    mydata = input('How are you? ')
    print(mydata)
使用不需要传递任何参数的
@staticmethod

@classmethod
def greeting():
    mydata = input('How are you?')
    print(mydata)
class mainClass:
    def greeting(self):
        mydata = input('How are you? ')
        print(mydata)
@staticmethod
def greeting():
    mydata = input('How are you? ')
    print(mydata)
使用需要传递
cls
参数的
@classmethod

@classmethod
def greeting():
    mydata = input('How are you?')
    print(mydata)
class mainClass:
    def greeting(self):
        mydata = input('How are you? ')
        print(mydata)
@staticmethod
def greeting():
    mydata = input('How are you? ')
    print(mydata)
以下是解决问题的三种方法

我还建议遵守有关命名类的规则:

类名通常应使用大写字母约定

这意味着您应该(在我看来)将您的类重命名为
MainClass


如果您有任何疑问或问题,请在下面留言,以便我可以在可能的情况下为您提供帮助。

您忘记使用
self
参数:)
def问候语(self):
您需要比“不工作”更具体。错误消息是什么?谢谢,那么为什么不起作用呢?
class C:def g(self):返回'hello world'instantialeclassc=C()instantialeclassc.g()