Class Properties
A property is a variable that lives in a class. It holds data for every object built from it.
Example
A class that has properties:
Output: complete Python program
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Emil", 36)
print(p1.name)
print(p1.age)
Access Properties
Dot notation is how you read a property of an object:
Example
Read an object's properties:
Output: complete Python program
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
car1 = Car("Toyota", "Corolla")
print(car1.brand)
print(car1.model)
Modify Properties
You can change a property's value on an object:
Example
Update the age property:
Output: complete Python program
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Tobias", 25)
print(p1.age)
p1.age = 26
print(p1.age)
Delete Properties
The del keyword removes a property from an object:
Example
Remove the age property:
Output: complete Python program
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("Linus", 30)
del p1.age
print(p1.name) # This works
# print(p1.age) # This would cause an error
Class Properties vs Object Properties
A property defined inside __init__() belongs to each object (an instance property).
One defined outside any method belongs to the class itself (a class property), and all objects share it:
Example
An instance property next to a class property:
Output: complete Python program
class Person:
species = "Human" # Class property
def __init__(self, name):
self.name = name # Instance property
p1 = Person("Emil")
p2 = Person("Tobias")
print(p1.name)
print(p2.name)
print(p1.species)
print(p2.species)
Modifying Class Properties
Changing a class property changes it for every object:
Example
Assign a new value to a class property:
Output: complete Python program
class Person:
lastname = ""
def __init__(self, name):
self.name = name
p1 = Person("Linus")
p2 = Person("Emil")
Person.lastname = "Refsnes"
print(p1.lastname)
print(p2.lastname)
Add New Properties
An object that already exists can still receive new properties:
Note: A property added this way exists only on that object, not on the others.
Example
Give an object an extra property:
Output: complete Python program
class Person:
def __init__(self, name):
self.name = name
p1 = Person("Tobias")
p1.age = 25
p1.city = "Oslo"
print(p1.name)
print(p1.age)
print(p1.city)