0

Let's say I define a class. I have a fun method, where I create self.x. I want to use self.x in a different method (reuse). How could I do that? Because I tried what I wrote and didn't work. Thanks!

class test:
    def __init__(self,t):
       self.t = t
    def fun(self):
       self.x = self.t+1
    def reuse(self):
       self.y = self.x 
4
  • Unless self.fun() is ever executed, self.x is not defined, so you'll need to ensure that self.fun() has been called atleast once prior to calling self.reuse() Commented Apr 17, 2020 at 5:58
  • so it would have to something like this: self.y = self.fun()? Commented Apr 17, 2020 at 5:59
  • 1
    self.fun() doesn't return anything. So you'll just need to add self.fun() before the self.y = self.x Commented Apr 17, 2020 at 6:23
  • @rdas If he adds self.fun() before self.y = self.x it calls the self.fun() every time he calls self.reuse(), which can modify the contents. Commented Apr 17, 2020 at 6:29

1 Answer 1

1

You need to create all the variables in the __init__ method. Try this:

class test:
    def __init__(self,t):
       self.t = t
       self.x = 0
       self.y = 0
    def fun(self):
       self.x = self.t+1
    def reuse(self):
       self.y = self.x 
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks but that's not what I want. I made a simplistic example, but in fun(), I compute many things and that I want to reuse and not compute again. Let me ask another question though. In fun, what is the difference between making the assigment self.x = self.t+1 and x = self.t+1. I think I know but I'd like the confirmation of someone more knowledgeable.
x = self.t+1 creates a local variable x in your method, that gets discarded when the method exits. self.x = self.t+1 updates the value of your instance's x attribute. But according to this last question, it seems that you over-simplified the example in your question, and that it doesn't really ask what you want...
When you use self.x = self.t+1 it will update the value of the class variable. When you use x = self.t+1 it will create a local variable to that function, which you can't access outside.
Wait a minute. I think your answer is correct. If I write the class the way you did. is self.y = self.x = self.t+1 ? In other words, self.y = self.t+1? or self.y = 0? I guess I can just run this and see what happens.
When you mention self.x = 0 in __init__ it will just execute once once when the instance is created. when you call other functions it will return use the values which are calculated before.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.