Infinity8 Infinity8 - 1 year ago 68
Python Question

Dynamic call to an Instance Variable

I have a dynamic string based on the current file's extension called "extension"

fileextension = os.path.splitext(file.filename)[1]
extension = fileextension.replace(".","")

Lets say extension = "pdf"

How would I be able to call the Ext.pdf() instance variable below?

class Ext:
def pdf(self):
self.filetype = "pdf - Adobe Portable Document Format"
def txt(self):
self.filetype = "txt - ASCII text file"
Ext = Ext()

I have tried:

Ext.filetype = getattr(Ext, extension)()

But this comes up with a blank entry

Answer Source

You called the instance attribute correctly. To fix your issue do not assign the result to the filetype attribute:

ext = Ext()
getattr(ext, extension)()

It did not work because you return None within pdf() and txt() method and assigned that to filetype attribute.

Note that I relabeled the instance of Ext to ext since it may be not a good idea to override a class definition by its instance.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download