Python函数返回不正确的值

rod*_*dit 1 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)
Run Code Online (Sandbox Code Playgroud)

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

<bound method File.getPath of <__main__.File instance at 0x3e99b00>>
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Rodit

C.B*_*.B. 5

test.getPath将返回函数或类实例的位置(如果是方法).您想要添加parens来调用该函数

print(test.getPath())
Run Code Online (Sandbox Code Playgroud)

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

def getPath(self):
    ...
Run Code Online (Sandbox Code Playgroud)

这将允许你这样做

test = File(parameter)
test.getPath()
Run Code Online (Sandbox Code Playgroud)

  • 此外,这些方法需要将"self"作为第一个参数. (2认同)