I have a class with many methods. How can I modify my methods so that they can also be accessed directly as a function without creating object of that class? Is it possible.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The methods will be “unbound” (meaning, essentially, that they have no
selfto work with). If the functions do not operate upon self, you can turn them into static-methods (which do not take aselffirst argument) and then assign them to variables to be used like functions.Like so:
Essentially, you need to ask yourself “What data does my method need to (er) function?” Depending on your answer, you can use
@staticmethodor@classmethodor you may find that you do in fact need aselfin which case you will need to create an object before trying to use its methods.That final case would look something like:
All of that aside, if you find that all of your methods are actually staticmethods, then it’s better style to refactor them out of the class into plain-old functions, which they really are already. You may have learned this “class as namespace” style from Java, but that isn’t correct in Python. Python namespaces are represented by modules.