Python Classes and Objects
A class is a blueprint for creating objects, and an object is one real copy created from that blueprint. Almost everything in Python is an object, like numbers, strings and lists. If you are new to the idea, read Python OOPS Introduction first.
Create a class
Use the class keyword. Here we create a class named MyClass with one property x.
class MyClass:
x = 5
print(MyClass)
<class '__main__.MyClass'>
The output tells us that MyClass is a class. By convention, class names start with a capital letter.
Create an object
Call the class name with brackets to create an object. Then use a dot to reach its properties.
class MyClass:
x = 5
p1 = MyClass()
print(p1.x)
5
You can create as many objects as you want from one class.
The __init__() method
A class like the one above gives the same value to every object. The special __init__() method runs automatically when an object is created, and it is used to give different values to each object. See What is the __init__() method?
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
p2 = Person("Maria", 28)
print(p1.name, p1.age)
print(p2.name, p2.age)
John 36
Maria 28
The first parameter self is the object itself. It is explained in What is the use of self?
Instance attributes and class attributes
- An instance attribute belongs to one object. It is created with
self.name = ...inside__init__(). - A class attribute is written directly inside the class and is shared by all objects.
class Dog:
species = "Canine" # class attribute
def __init__(self, name):
self.name = name # instance attribute
d1 = Dog("Tommy")
d2 = Dog("Bruno")
print(d1.species, d2.species)
print(d1.name, d2.name)
Canine Canine
Tommy Bruno
Modify and delete properties
p1 = Person("John", 36)
p1.age = 40 # modify
print(p1.age)
del p1.age # delete a property
del p1 # delete the whole object
40
After del p1 the name p1 no longer exists, and using it raises a NameError.
The pass statement
A class cannot be empty. If you want to write it later, use pass.
class Student:
pass
Print an object
If you print an object directly, Python shows its class and memory address, like <__main__.Person object at 0x...>. The address is different each time. To show something useful, add a __str__() method, as explained in Python Object Methods.
Summary
- A class is a blueprint and an object is a real copy of it.
- Use
__init__()to set the starting values. - Instance attributes belong to one object, class attributes are shared.
- Use
delto delete a property or an object. - Next: Python Object Methods.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |