Python 3 - 调用方法来更改类中的另一个方法

问题描述 投票:1回答:2

试着上课,我可以让狗停下来

我正在努力解决在我的状态方法中写入的内容,以及在调用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方法并使输出更改依赖于调用

methods
2个回答
0
投票

使用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

0
投票

也许你可以使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"
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.