Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Definition of custom class and different methods

I have below definition:

def fun1(x) :
    return x + 2

class my_class :
    def fun1(x) :
        return x + 22
    def fun2(x) :
        return fun1(x) + 33

print(my_class.fun2(10))

However this returns 45, whereas I am expecting 65 (10 + 22 + 33).

Where am I making a mistake?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This can be a way out but, not a recommended style:

class my_class:
    def fun1(x) :
        return x + 22
    def fun2(x) :
        return my_class.fun1(x) + 33
my_class.fun2(10)

Another unorthodox way:

class my_class:
    def fun1(x) :
        return x + 22
    @classmethod
    def fun2(cls,x) :
        return cls.fun1(x) + 33
my_class.fun2(10)

The best way I can think of:

def fun1(x) :
    return x + 2

class my_class :
    def fun1(self,x) : 
        return x + 22
    def fun2(self,x) :
        return self.fun1(x) + 33 #refering to instance method self.fun1

print(my_class().fun2(10)) # my_class() is a object
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading