1

I made the following simple class in Visual studio community edition:

class Check(object):
def __init__(self):
    self.t = 5

but when run

from Check import Check
try:
    print(Check.t)
except Exception as Err:
    print(str(Err))

or

    import Check
    try:
       print(Check.t)
    except Exception as Err:
       print(str(Err))

I get the error of:

The object 'Check' has no attribute 't'

It is also weird because the keyword 'self' is not shown as Python keyword or Buildin func.

  • Please [edit] your question title to something that explains the problem you're having or question you're asking in a way that will have meaning to a future user of the site scanning through a list of search results. You've provided no information that isn't already available in the tags, which is not useful or meaningful at all. Thanks. – Ken White Feb 05 '20 at 13:29

2 Answers2

0

You've gotta instantiate the Object of Check before being able to access it.

This can be done by the following

from Check import Check
try:
    print(Check().t)
except Exception as Err:
    print(str(Err))

When you try to call Check.t it's trying to access the class element 't' which is non existent.

0

The information regarding visual studio community is redundant here.

The problem lies with how you're defining and calling your class. You've created a class(the blueprint) but haven't created any instance (actual object) while calling the attribute (variable t).

Let's say you have a module named check.py where you've defined your simple class.

# check.py

class Check:
    def __init__(self):
        self.t = 5

Now import the class Check from module check.py

from check import Check

# create an instance of the class
ins = Check()

# access and print the attribute
try:
    att = ins.t
    print(att)
except Exception as err:
    print(str(err))
Redowan Delowar
  • 1,580
  • 1
  • 14
  • 36
  • Thanks guys. Any idea why the keyword 'self' is not recognized as Python Build-in? in Class definition, its color and style is the same as regular parameter. –  Feb 05 '20 at 15:47
  • Self is nothing but a placeholder for the instance itself. It's not implicit to conform with python's philosophy. You can read about that [here.](https://stackoverflow.com/questions/2709821/what-is-the-purpose-of-the-word-self-in-python) – Redowan Delowar Feb 05 '20 at 16:14