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()
或者声明问候语
aclassmethod
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()