Frage

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

War es hilfreich?

Lösung

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()
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top