Python 3 - 调用方法来更改类中的另一个方法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 3 - 调用方法来更改类中的另一个方法相关的知识,希望对你有一定的参考价值。
试着上课,我可以让狗停下来
我正在努力解决在我的状态方法中写入的内容,以及在调用comeHere()和stop()方法时如何使状态调用的输出更改
class Dog:
def setYear(self, i):
if len(i) == 4:
self.__year = i
def getYear(self):
return self.__year
def status(self):
def comeHere(self):
def stop(self):
def main():
watson = Dog()
watson.setYear(2011)
print("The dog is born in ",watson.getYear())
print(watson.status())
print("trying to make the dog come")
watson.comehere()
print("Come here boy... ",watson.status())
print("Trying to make him stop again")
watson.stop()
print("Stop! ... ",watson.status())
main()
Want the output to be like this
The dog is born in 2011
The dog is standing
Trying to make the dog to come
Come here boy... the dog is coming
Trying to make him stop again
Stop! ... The dog is standing
如何在status()
之前调用status方法并使输出更改依赖于调用
答案
使用status作为变量not function
class Dog:
def __init__(self):
self.status="The dog is standing"
def setYear(self, i):
if len(str(i)) == 4:
self.__year = i
def getYear(self):
return self.__year
def comeHere(self):
self.status="the dog is coming"
def stop(self):
self.status="The dog is standing"
watson = Dog()
watson.setYear(2011)
print("The dog is born in ",watson.getYear())
print(watson.status)
print("trying to make the dog come")
watson.comeHere()
print("Come here boy... ",watson.status)
print("Trying to make him stop again")
watson.stop()
print("Stop! ... ",watson.status)
产量
The dog is born in 2011
The dog is standing
trying to make the dog come
Come here boy... the dog is coming
Trying to make him stop again
Stop! ... The dog is standing
另一答案
也许你可以使status
成为Dog
类中的一个变量,并在调用其中一个函数时对其进行修改。
class Dog:
def __init__(self):
self.status = None
def setYear(self, i):
if len(i) == 4:
self.__year = i
def comeHere(self):
self.status = "Dog is coming"
watson = Dog()
watson.comeHere()
print(watson.status) # returns 'Dog is coming"
以上是关于Python 3 - 调用方法来更改类中的另一个方法的主要内容,如果未能解决你的问题,请参考以下文章