Phorce
Phorce

Reputation: 2674

Python - Access class member without initialization of object

In the Python module "Wave" I can use the following syntax:

import wave
wave.open("test.wav", "rb")

This works perfectly fine.Let's say I wanted to use my own initialization of a class:

class Wave():

   def __init__(self):
       pass; 

   def Open(self, fileName, Type):
       return True; # Just testing 

Now If I have "main" which calls this class, why can't I do the following?:

if Wave.Open("testing.wav", "rb"): 
   print "The file is open"

TypeError: unbound method Open() must be called with Wave instance as first argument (got str instance instead)

Upvotes: 1

Views: 407

Answers (3)

alko
alko

Reputation: 48387

Other option, if you want your open method be class-specific, is @classmethod decorator, i.e.

class Wave():
   def __init__(self):
       pass;
   @classmethod 
   def open(cls, filename):
       print '{}.open method with args "{}"'.format(cls, filename)
       return True; # Just testing 

class SubWave(Wave): pass

and use as follows:

>>> Wave.open('filename')
__main__.Wave.open method with args "filename"
True

>>> SubWave.open('filename')
__main__.SubWave.open method with args "filename"
True

Upvotes: 3

Lix
Lix

Reputation: 48006

As the error states, you need an instance of the Wave class to call the Open method. Something like this should work:

if Wave().Open("testing.wav", "rb"): 
   print "The file is open"

Note the parenthesis after Wave - that's what creates the new instance.

If you want to be able to call this method without having an instance of the Wave class you could add a @staticmethod decorator to the Open function. This will allow you to call the method as you do in the code you provided.

Upvotes: 3

NPE
NPE

Reputation: 500933

To be able to call it like this you need to make Open a static method:

@staticmethod
def Open(fileName, Type):
   ...

The difference between your code and the example you give at the start is that wave is a module, and Wave is a class. You could turn Wave into a module and have Open be a top-level function within that module.

Upvotes: 4

Related Questions