Paul's Python CoursePPC

Attributes

Not met yet

An attribute is a value kept on an object: self.rider inside the class, red.rider from outside. Read and change attributes with a dot. A name assigned without self. inside a method is only a local variable, gone when the method ends, and reading an attribute that was never set is an AttributeError.

Try it

main.py
class Bike:
    def __init__(self, number):
        self.number = number
        self.rider = None

red = Bike(7)
red.rider = "Yahya"
print(red.number, red.rider)

Output

Press Run and what your program prints shows up here.

Easy to get wrong

  • Thinks assigning a name inside a method, like rider = rider, sets an attribute on the object.
  • Thinks reading an attribute that was never set gives None rather than an AttributeError.

Where it comes up