我最近决定开始学习基本的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()更多推荐
发布评论