Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"self.data" usage in python

Hello I have a question about attribute usage in Python. I learned that in function definition we can assign some new attributes for objects for example: self! However, when try to use that I got an error which is "... instance has no attribute 'data'

class Lazy:
    def __call__(self, num):
            if num is None:
                    return self.data
            # It changes the current object in-place,
            # by reassigning the self attribute.
            else:
                    self.data += num

This is my little code. I'm very new at this. I couldn't figured out what is wrong. Thank you very much.

like image 378
jdyg Avatar asked Sep 02 '26 08:09

jdyg


1 Answers

You are only assigning self.data if num is None, so it can happen that you try to access it before it has been assigned. To prevent this, you could initialize it in the constructor:

class Lazy:
    def __init__(self):
        self.data = 0

    def __call__(self, num):
        if num is None:
            return self.data
        else:
            self.data += num

Here's what sequence of events causes your error:

  1. You create a new instance of your class. At this point, Python knows nothing about self.data:

    lazy = Lazy()
    
  2. You call it passing None:

    lazy(None)
    
  3. Now, Python enters __call__ and because the if condition evaluates to True it tries to return self.data. Wait a minute... it still doesn't know what self.data is... so it spits out an error.

In order to prevent this, you always have to assign your attributes before trying to do something with their values (for instance, returning them from a function). It doesn't have to be in the constructor: just before the first time Python tries to access the attribute. This is true for any variable, i.e. the following is impossible:

print(a) # How do you expect Python to know the value of a?
a = 5    # too late to assign it now...
like image 138
Adam Avatar answered Sep 03 '26 22:09

Adam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!