Q:

access python class variable from method

I am new to Python, and am trying to figure out how to access the global variable count within the repr method in the Student class below:
class Student(object):
    count = 0
    def __init__(self, **kwargs):
        self.name = kwargs.get("name")
        self.age = kwargs.get("age")
        Student.count += 1
    def __repr__(self):
        try:
            return "name: %s, age: %d" % (self.name, self.age)
        except TypeError:
            print "student number: %d" % (Student.count)

When I create an instance, such as student = Student, and the try to print the variable student, I get the following error:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "school.py", line 23, in __repr__
    print "student number: %d" % (Student.count)
NameError: global name 'count' is not defined

Thanks.

A:

You can access class properties as well using self. Not that in your case, your error handling in __repr__ isn’t necessary. In a method, self will always be correct (unless you really mess something up), so you can just assume that you can access self properly. As you initialize name and age in the initializator, you can also assume that both properties exist:
class Student (object):
    count = 0
    def __init__ (self, **kwargs):
        self.name = kwargs['name']
        self.age = kwargs['age']
        self.count += 1

    def __repr__ (self):
        return "name: %s, age: %d" % (self.name, self.age)

Instead of accepting just **kwargs, it might be a good idea to actually ask for name and age as proper parameter in the initializator. Since you do expect name and age to be specified, incorrectly calling your constructor will fail early that way:
def __init__ (self, name, age, **kwargs): # **kwargs in case you want to accept more
    self.name = name
    self.age = age
    self.count += 1

That all being said, the error you show shouldn’t happen. There shouldn’t be an exception being thrown in __repr__, and Student.count should be accessible as well. So you are probably calling __repr__ in some weird way. The proper way would be something like this:
a = Student(name='Peter', age=15)
print(repr(a))

