M&C 5: Correct syntax for using classes and objects is hard

When students begin to learn how to use classes and objects in Python, using the correct syntax can be a challenge. The errors may produce  messages not yet meaningful to students. Like with many topics, the key lies in giving students opportunities to practice and let them identify errors in code.

The following code contains common mistakes students make when they start using classes and objects.

# Incorrect Code
class circle:
    def circle(cen, rad):
        center = cen
        radius = rad
        return circle

    def get_radius():
        return radius

c = circle([0,0], 10)
print get_radius(c)

Problems in the code:

  • When using an object method, the syntax needs to be object.method()
    • Line 12 get_radius(c) should be c.get_radius()
  • The constructor should be a method called __init__() rather than circle()
    • Line 3 def circle(cen, rad) should be def __init__(cen, rad):
  • The method should have self as the argument, which refers the object
    • Line 8 def get_radius() should be def get_radius(self)
    • Line 3 def __init__(cen, rad) should be def __init__(self, cen, rad):
  • To get the values of attributes, we need to use self to refer the object
    • Line 4 center = cen should be self. center = cen
    • Line 5 radius = rad should be self.radius = rad
    • Line 9 return radius should be return self.radius
  • The constructor returns the object implicitly and no return needed in __init__ method
    • remove Line 6 return circle
  • In Python, the convention is to capitalize the class name
    • Line 2 class circle should be class Circle

The following code is fixed:

# Fixed Code
class Circle:
    def __init__(self, cen, rad):
        self.center = cen
        self.radius = rad

    def get_radius(self):
        return self.radius

c = Circle([0,0], 10)
print c.get_radius()