Classes & Objects Flashcards
Creating a Python Class
Create a class using the class keyword.
class MyClass:
#define class
Creating an Object from a Class
You can create a new instance of an object by using the class name + ()
class Car:
pass
my_toyota = Car()
Class Methods
You can create a function that belongs to a class, this is known as a method.
class Car:
def drive(self):
print(“move”)
my_honda = Car()
my_honda.drive()
Class Variables
You can create a variable in a class. The value of the variable will be a available to all objects created from the class.
class Car:
colour = “black”
car1 = Car()
print(car1.colour) #black
The init method
You will see “building car” printed.
The init method is called every time a new object is created from the class.
class Car:
def init(self):
print(“Building car”)
my_toyota = Car()
Class Properties
You can create a variable in the init() of a class so that all objects created from the class has access to that variable.
class Car:
def init(self, name):
self.name = “Jimmy”
Class Inheritance
When you create a new class, you can inherit the methods and properties of another class.