0

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'
>>> 
4
  • a = test() print(a.testy) Commented May 19, 2018 at 6:48
  • You never instantiate your class. Commented May 19, 2018 at 6:48
  • So a acts as a pointer to the class, and not a member actual class, right? Commented May 19, 2018 at 6:50
  • 1
    Possible duplicate of Python function not accessing class variable Commented May 19, 2018 at 6:50

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

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.