【问题标题】:How do I reset or replace a function in a class used with inheritance method after using it?使用继承方法后如何重置或替换使用继承方法的类中的函数?
【发布时间】:2020-10-17 12:23:09
【问题描述】:

我只想重置“self.news”变量或在我在下面创建的类中获取新值。但是当我运行这三个函数时。所有的值都恢复到原来的状态。 并且我之前使用的功能无效。如何仅更改或重置变量'self.nexts'。非常非常感谢。

class new:
    def __init__(self, name=None, nexts=None):
        self.nexts = nexts
        self.name = name

    def one(self):
        self.nexts = 2
        return self.nexts

    def two(self):
        self.nexts = 1
        self.name = 'What'
        return self.nexts

    def three(self):
        self.__init__()
        print(self.name)
        print(self.nexts)


a = new()

print(a.one())
#output = 2
print(a.two())
#output = 1, hate
a.three()
#output = None, None

【问题讨论】:

标签: python python-3.x oop data-science


【解决方案1】:

您可以使用您希望将实例变量重置为的值进行初始化,如下所述:How to call the constructor from within member function

def three(self):
    self.__init__(None, self.nexts)
    print(self.name)
    print(self.nexts)

a.three()
# Output: None, 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 2012-10-01
    • 1970-01-01
    • 2016-08-15
    • 2014-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多