Python函数返回不正确的值

时间:2014-03-24 20:08:27

标签: python python-idle

我最近决定开始学习基本的python ... 我正在创建一个简单的python File类,类似于.NET框架中使用的类。

到目前为止,我有以下代码:

import os

class File:
    def __init__(self, filename=""):
        self.path = filename
        self.pathwithoutfilename, self.extwithdot = os.path.splitext(filename)
        self.ext = self.extwithdot.replace(".", "")

    def exists():
        rbool = False
        if(os.path.exists(self.path)):
            rbool = True
        else:
            rbool = False

        return rbool

    def getPath():
        return self.path


test = File("/var/test.ad")
print(test.path)
print(test.extwithdot)
print(test.ext)
print(test.getPath)

但是,当我运行此代码时,(我在Ubuntu上使用python 2.7)它会为test.getPath函数打印它:

<bound method File.getPath of <__main__.File instance at 0x3e99b00>>

我一直在改变和编辑我的代码一段时间但我没有取得任何成功...我希望getPath函数返回之前设置的self.path值......

由于

Rodit

1 个答案:

答案 0 :(得分:5)

test.getPath将返回函数或类实例的位置(如果是方法)。您想要为调用函数

添加parens
print(test.getPath())

注意,正如Lukas Graf所指出的,如果能够从实例化对象调用它们,那么你的类实现需要在定义方法时传递self标识符,即

def getPath(self):
    ...

这将允许你做

test = File(parameter)
test.getPath()
相关问题