CS101 Classes
Learn how to create Classes in Python
StartKey Concepts
Review core concepts you need to learn to master this subject
Python repr
method
Python class methods
Instantiate Python Class
Python Class Variables
Python init method
Python type() function
Python class
Python dir() function
Python repr
method
Python repr
method
class Employee:
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
john = Employee('John')
print(john) # John
The Python __repr__()
method is used to tell Python what the string representation of the class should be. It can only have one parameter, self
, and it should return a string.
Introduction to Classes
Lesson 1 of 1
- 3A class doesn’t accomplish anything simply by being defined. A class must be instantiated. In other words, we must create an instance of the class, in order to breathe life into the schematic. …
- 4A class instance is also called an object. The pattern of defining classes and creating objects to represent the responsibilities of a program is known as Object Oriented Programming or OOP. I…
- 5When we want the same data to be available to every instance of a class we use a class variable. A class variable is a variable that’s the same for every instance of the class. You can define a…
- 7Methods can also take more arguments than just self: class DistanceConverter: kms_in_a_mile = 1.609 def how_many_kms(self, miles): return miles * self.kms_in_a_mile converter = DistanceCo…
- 8There are several methods that we can define in a Python class that have special behavior. These methods are sometimes called “magic,” because they behave differently from regular methods. Another …
- 9We’ve learned so far that a class is a schematic for a data type and an object is an instance of a class, but why is there such a strong need to differentiate the two if each object can only have t…
- 10Instance variables and class variables are both accessed similarly in Python. This is no mistake, they are both considered attributes of an object. If we attempt to access an attribute that is ne…
- 12Attributes can be added to user-defined objects after instantiation, so it’s possible for an object to have some attributes that are not explicitly defined in an object’s constructor. We can use th…
- 13One of the first things we learn as programmers is how to print out information that we need for debugging. Unfortunately, when we print out an object we get a default representation that seems fai…