< Back

Activity 33

Class Attributes

Objects are instances of some defined class. Attributes are data members of objects. They are unique to each individual instances of the class. Attributes can be added to an object an any time, but traditionally are defined in the constructor of the object. Consider the following examples of classes, to get the hang of working with these entities.


Consider the following simple class:

class Foo:
    def __init__(self, a, b):
        self.a = a
        self.b = b
   
    def mutate_a(self, new_a):
        self.a = new_a

    def mutate_b(self, new_b):
        self.b = new_b

    def print_foo(self):
        print(self.a, self.b)

What will the following examples print to the terminal?

  1. bar = Foo(1, 2)
    print(a, b)
    
  2. bar = Foo(1, 2)
    print(bar.a, bar.b)
    
  3. bar = Foo(1, 2)
    print(bar.print_foo())
    
  4. bar = Foo(1, 2)
    print(bar.a)
    mutate_a(3)
    print(bar.a)
    
  5. bar = Foo(1, 2)
    print(bar.a)
    bar.mutate_a(3)
    print(bar.a)
    
  6. bar_1 = Foo(1, 2)
    bar_2 = bar_1
    bar_1.mutate_a(3)
    print(bar_1.a, bar_2.a)
    
  7. bar_1 = Foo(1, 2)
    bar_2 = Foo(1, 2)
    bar_1.mutate_a(3)
    print(bar_1.a, bar_2.a)
    
  8. bar = Foo(1, 2)
    bar.a = 3
    print(bar.a)
    
  9. bar = Foo(1, 2)
    bar.c = 3
    print(bar.c)
    
  10. bar = Foo(1, 2)
    print(bar.c)