lempy
lempy

Reputation: 103

Calling an object of a method of a class within another method of the same class

I was trying to call the objects of a method in one of my classes within antoher method of the same class. Below you can find a small example of how I tried to do it:

class example_class():
    
    def some_method(self):
        #... calculate something ...
        a = 1 
        b = 2

    def second_method(self):
        call = self.some_method()
        c = call.a + call.b

If I do this, I get the error: "'NoneType' object has no attribute 'a'". I am sure this is a fearly basic problem, but I am using classes, objects and methods for the first time and would really appreciate the help!

Thank you in advance and stay safe!

Upvotes: 0

Views: 2436

Answers (2)

crt0o
crt0o

Reputation: 48

This should work

class example_class:
    def some_method(self):
        self.a = 1
        self.b = 2
    def second_method(self):
        self.some_method()
        print(self.a + self.b)

You can't access a method's local variables from another method, you should store them as attributes.

Upvotes: 1

Ricardo
Ricardo

Reputation: 691

class example_class():

    def some_method(self):
        #... calculate something ...
        self.a = 1 
        self.b = 2

    def second_method(self):
        # call = self.some_method()
        c = self.a + self.b

Upvotes: 3

Related Questions