【问题标题】:How to access return class values in another function python如何在另一个函数python中访问返回类值
【发布时间】:2016-11-18 14:37:04
【问题描述】:

我有课

class Sums():
    #someCode
    return result

如果我将类导入另一个文件并且我想使用返回的“结果”的值。我如何访问这个对象?

另外,如果我有一些 Sums 类

class Sums():
    def percent():
        #someCode
        #return Result
    def overall():
        # To be able to use the value of Result in the prior code
        # i try to access this object by using an object of sums
        # a = Sums()
        # result  = a.percent()

我正在尝试理解 py 中的 oop,但我在如何使用和引用已创建的对象方面遇到了困难。

在同一个类的函数中,当它们被导入时,如何使用类函数的返回值来保存程序所需的一些信息 谢谢

【问题讨论】:

    标签: python-2.7 class oop


    【解决方案1】:

    您混淆了类和方法。类保存信息片段,但不运行任何代码。但是,它们可以包含具有可运行代码的方法。这些方法可以返回值,但类不能。

    试试reading through this tutorial 看看它是否更有意义。祝你好运!

    【讨论】:

    • 但是如果我确实在类中创建方法,我如何访问返回值?还是我不能?在后续角色中使用它们。您提供的链接中的示例
    • class BankAccount: def __init__(self): self.balance = 0 def withdraw(self, amount): self.balance -= amount return self.balance def deposit(self, amount): self. balance += amount return self.balance >>> a = BankAccount() >>> b = BankAccount() >>> a.deposit(100) 100
    • 假设我想使用下面一些代码中返回的 self.balance 的值。我怎么做?抱歉,我对平台不熟悉。
    • 我只是为你整理了一个例子。转到此处并按运行:repl.it/E2RO/1。希望对您有所帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-02
    • 2019-03-29
    • 1970-01-01
    • 2019-04-03
    • 2021-11-02
    • 2021-12-11
    • 1970-01-01
    相关资源
    最近更新 更多