1

In python ,how can I use a method of a class in a normal function outside the class?

Class Python:
    def __init__(self,a):
        self.__a=a
    def get_a(self):
        return self.__a
def normal_func:
    var=Python.get_a()
    print(var)
Akash
  • 21
  • 4
  • 1
    Does this answer your question? [Class method differences in Python: bound, unbound and static](https://stackoverflow.com/questions/114214/class-method-differences-in-python-bound-unbound-and-static) – Mandera Nov 28 '20 at 09:57
  • `Python` is the class. But your method, `get_a` is an instance method, that relies on internal state (i.e. it uses `self`). Thus, **like any instance method** it should be used on an instance. – juanpa.arrivillaga Nov 28 '20 at 10:11

1 Answers1

0

The get_a() method presented in the question is an instance method. This means that all objects of the class Python can call the get_a() method. The easiest way to use the object methods of a class, in a function, is to create an object of the class and then carrying out any operations on it. So the code above will be re-factored to:

class Python:
    def __init__(self,a):
        self.__a=a
    def get_a(self):
        return self.__a
def normal_func:
    P = Python('a')
    var=P.get_a()
    print(var)

If the normal_func is supposed to do perform differently for different values of <PythonObject>.a, I would suggest that you add the object as a parameter for the function. So the new function would be something like this:

def normal_func(PythonObject):
    var = PythonObject.get_a()
    print(var)
Ashwin
  • 31
  • 3