Lesson 76 +10 XP

Class Properties and Methods

Class Properties and Methods

Attributes hold data; methods define behavior. Together they make a complete object.

Properties (attributes)

Set on the object, usually in __init__:

class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

Methods (functions of the class)

class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

    def introduce(self):
        print(f"I am {self.name}")

    def is_passing(self):
        return self.grade >= 60

s = Student("Ada", 85)
s.introduce()          # I am Ada
print(s.is_passing())  # True

Instance vs class attributes

  • Instance attributes are set on self; each object has its own.
  • Class attributes live on the class; all objects share them.
class Student:
    school = "Python High"  # class attribute

    def __init__(self, name):
        self.name = name   # instance attribute

Getters and setters

Simple getters/setters are optional because attributes are public:

def get_name(self):
    return self.name

def set_name(self, value):
    self.name = value

The pass rule

A class body can't be empty; use pass:

class Empty:
    pass

TL;DR

  • Attributes store data; methods define behavior.
  • Instance attributes use self; class attributes live on the class.
  • Methods always take self first.
  • pass fills an empty class body.