Attribute created in one method doesn't exist in other method
attributes, class, python
Solution
Short answer, no. The problem with your code is that each time you create a new instance.
Edit: As abarnert mentions below, there is a big difference between `Class.a` and `c.a`. Instance attributes (the second case) belong to each specific object, whereas class attributes belong to the class. Look at abarnert's comment below or the discussion here for more info.
Your code is equivalent to
c1 = Class()
c1.method_1() # defines c1.a (an instance attribute)
c2 = Class()
c2.method_2() # c2.a undefined (the c2 instance doesn't have the attribute)
You probably want to do somthing like
c = Class()
c.method_1() # c.a = 1
c.method_2() # c.a = 2
print "c.a is %d" % c.a # prints "c.a is 2"
Or probably even better would be to initialize `c` with an `a` attribute
class Class:
def __init__(self):
self.a = 1 # all instances will have their own a attribute
Problem
Here I have an attribute 'a', which is defined in first class method and should be changed in second. When calling them in order, this message appears: AttributeError: 'Class' object has no attribute 'a' The only way I've found - define 'a' again in second method, but in real code it has long inheritance and app will be messed. Why doesn't it work? Isn't self.a equal to Class.a? ``` class Class(object): def method_1(self): self.a = 1 def method_2(self): self.a += 1 Class().method_1() Class().method_2() ```