E. Aly
E. Aly

Reputation: 331

accessing a variable created inside a method from another method in a python class

I want to access a variable created inside some method from another method. For instance:

class text():
    def __init__(self, text):
        self.txt = text

    def sp1(self):
        self.a = self.txt.split(',')[0]
        self.b = self.txt.split(',')[1]
        return self.a

    def sp2(self):
        return self.b

Now when I try to apply this like in:

T = text('I woke up early, it is school today')

print(T.sp2())

I get an error that 'text' object has no attribute 'b'

I don't understand where the problem seems to be?

Upvotes: 3

Views: 1190

Answers (5)

Mehdi Aminazadeh
Mehdi Aminazadeh

Reputation: 1

class text: def init(self, text): self.txt = text

def sp1(self):
    self.a = self.txt.split(',')[0]
    self.b = self.txt.split(',')[1]
    return self.a
    
def sp2(self):
    self.sp1()
    return self.b

Upvotes: 0

class text():
    def __init__(self, text):
        self.txt = text
        self.a = self.txt.split(',')[0]
        self.b = self.txt.split(',')[1]

    def sp1(self):
        return self.a

    def sp2(self):
        return self.b

Upvotes: 0

E. Aly
E. Aly

Reputation: 331

So I guess the solution in this case would be to call sp1 inside sp2

....

def sp2(self):
    self.sp1()
    return self.b

Upvotes: 1

J Lossner
J Lossner

Reputation: 139

You did not define self.b prior to calling it.

(Edited to remove false assumption that you can only define the attributes in __init__)

Upvotes: 0

quamrana
quamrana

Reputation: 39354

Perhaps you mean:

T = text('I woke up early, it is school today')
T.sp1()
print(T.sp2())

Upvotes: 2

Related Questions