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)
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.
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.
Other option, if you want your open method be class-specific, is @classmethod decorator, ie
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
链接地址: http://www.djcxy.com/p/54292.html
上一篇: 教新手入门的最佳方法?
下一篇: 无需初始化对象的访问类成员
