繁体   English   中英

Python函数返回不正确的值

[英]Python function returning incorrect value

我最近决定开始学习基本的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设置的self.path值。

谢谢

罗迪特

test.getPath将返回函数或类实例的位置(如果使用方法)。 您要添加括号以调用该函数

print(test.getPath())

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

def getPath(self):
    ...

这将使您能够

test = File(parameter)
test.getPath()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM