Simple Class & Objects
A class creates a new type where objects are instances of the class.
You can think of class as a blueprint, it simply describes how to make something. You can create lots of objects of a particular kind from that blueprint, technically objects are called instances of that class.
The syntax of defining a class:
class MyClassName:
data attributes...
functions...
The first line defines the class container, which starts with the keyword class
and the class name, then a colon : ends the line.
All indented statements (4 spaces) form the body of the class. The class body consists of all the component statements defining class members: data attributes(variables) and functions(also called methods).
Class names are usually capitalized,
MyClassNameLikeThis
, but this is only a convention, not a requirementEverything in a class is indented, just like the code within a
function, if statement, for loop
. The first thing not indented is not in the class.
See a very simple class example:
Apple class
Let's make a simple class to represent an apple, this class has only one variable color
:
class Apple:
name = 'Fuji'
The first line defines the class Apple
, in the indented class body, there is only one attribute: the class variable named name
, which is set to a value of 'Fuji'
.
When creating a class Apple
, I haven't actually created an apple object yet. Instead, what I've created is a sort of instruction manual for constructing "Apple"
objects.
Class Instantiation, Object
Class instantiation means we create an object/instance of the class. this uses function notation: using the name of the class followed by a pair of parentheses.
Using the class to create an object:
x = MyClassName()
This creates a new instance of the class and assigns this object to the local variable x
. For now, just pretend that a class object is a parameterless function that returns a new instance/object of the class.
x
, as an instance of the class will get all the attributes defined in the class. Accessing the attributes of x using dot notation: x.attribute
Let's create an object using class Apple
a1 = Apple() # create an object
print( a1.name ) # Fuji (access attribute)
a1.name = 'Gala' # assign a new value to attribute
print( a1.name) # Gala
We create an Apple
object, a1
, by calling the class name with an parenthesis(it's empty in this example, just pretend it's a function with no input parameters). a1
as an instance/object of Apple
class, it has attribute, name
, that starts at value 'Fuji'
, we can access it by using objectName.attribute
, here it's a1.name
; we can also assign new value to the attributes like a1.name = 'Gala'
. This is data attribute.
Objects, created from a class, have attributes defined in the class:
data attributes, function attributes(also called methods).
Next lesson: Functions belong to an object, methods.