Python函数返回不正确的值(Python function returning incorrect value)

编程入门 行业动态 更新时间:2024-10-24 10:17:34
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值...

谢谢

Rodit

I have recently decided to start learning basic python... I am creating a simple python File class, similar to the one used in the .NET framework.

So far, I have the following code:

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)

However, when I run this code, (I am using python 2.7 on Ubuntu) it prints this for the test.getPath function:

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

I have been changing and editing my code for a while now but I have not had any success... I would like the getPath function to return the self.path value set earlier...

Thanks

Rodit

最满意答案

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

print(test.getPath())

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

def getPath(self): ...

这将允许你这样做

test = File(parameter) test.getPath()

test.getPath will return the location of the function or instance of class (in case of a method). You want to add parens to call the function

print(test.getPath())

Note, as pointed out by Lukas Graf, your class implementation needs to pass the self identifier when defining methods if they are to be able to be called from an instantiated object, i.e.

def getPath(self): ...

This will allow you to do

test = File(parameter) test.getPath()

更多推荐

本文发布于:2023-08-06 18:52:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1454045.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不正确   函数   Python   incorrect   returning

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!