Asked By – Curious2learn
I ran into unbound method error in python with the code
import random class Sample(object): '''This class defines various methods related to the sample''' def drawSample(samplesize,List): sample=random.sample(List,samplesize) return sample Choices=range(100) print Sample.drawSample(5,Choices)
After reading many helpful posts here, I figured how I could add
@staticmethod above to get the code working. I am a python newbie. Can someone please explain why one would want to define static methods? Or, why are not all methods defined as static methods?
Now we will see solution for issue: What is the advantage of using static methods?
Static methods have limited use, because they don’t have access to the attributes of an instance of a class (like a regular method does), and they don’t have access to the attributes of the class itself (like a class method does).
So they aren’t useful for day-to-day methods.
However, they can be useful to group some utility function together with a class – e.g. a simple conversion from one type to another – that doesn’t need access to any information apart from the parameters provided (and perhaps some attributes global to the module.)
They could be put outside the class, but grouping them inside the class may make sense where they are only applicable there.
You can also reference the method via an instance or the class, rather than the module name, which may help the reader understand to what instance the method is related.
This question is answered By – Oddthinking
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0