John Hao
John Hao

Reputation: 39

Why can't I access an class variable defined in __init__ from outside of the class?

I was wondering about classes and how I can access their values from the outside with either printing it or using the _str__ function. I came across this question: Python function not accessing class variable

Then I did this test in Shell, but it didn't work as expected. I wonder why the other answer worked, but not this one.

(edit) My question was answered by how to instantiate a class, not instance variables.

>>> class test:
    def __init__(self):
        self.testy=0
    def __str__(self):
        return self.testy


>>> a=test
>>> b=test
>>> print(a)
<class '__main__.test'>
>>> a
<class '__main__.test'>
>>> a.testy
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    a.testy
AttributeError: type object 'test' has no attribute 'testy'
>>> 

Upvotes: 0

Views: 2609

Answers (2)

user5777975
user5777975

Reputation:

You had done a mistake while creating objects, please find below differences:

class test:
def __init__(self):
    self.testy=0
def __str__(self):
    return self.testy

a = test()
b = test()
a.testy
       output: 0

What you have done:

c = test
d = test
c.testy
Traceback (most recent call last):
  File "<input>", line 1, in <module>
AttributeError: type object 'test' has no attribute 'testy'

Explanation:

when you are creating objects for a class use object = class_name()

**https://docs.python.org/3/tutorial/classes.html#class-objects

Upvotes: 1

Martijn
Martijn

Reputation: 417

You define your variable inside init, which is only called when the class is instantiated. For a longer explanation, I'd refer you to the first answer on the question you linked.

Upvotes: 0

Related Questions