The first step in using classes is creating the class definition or “blueprint.” To create a new class, the syntax is like functions, but you use the class keyword instead of def. Within the indentation of this class block, we would write the blueprint for our class attributes and methods. Don’t worry about those for now though; we’ll go over those on Tuesday and Wednesday. For now, we’ll just use the keyword pass. Let’s check out an example:
# creating your first class class Car( ): pass # simply using as a placeholder until we add more code tomorrow
Go ahead and run the cell. Nothing will happen, but that’s good because it means it worked! All classes will be created with the same structure, except instead of writing pass, we’ll fill the block with code that gives objects features.
Note in python, data types are also classes at their base. printing out the type of an integer results in .
Creating an Instance
Now that we know how to create the class definition, we can begin to understand how to create an instance of an object. Like storing a data type into a variable name, we use similar syntax, except after the name of the class, we use parenthesis. We’ll go over what these parentheses are used for in tomorrow’s lesson. Let’s check it out:
# instantiating an object from a class class Car( ): # parens are optional here pass ford = Car( ) # creates an instance of the Car class and stores into the variable ford print(ford)
Go ahead and run the cell. You’ll get an output like “<__main__.Car object at 0x0332DB>”. This is describing the class that the instance was built from “Car,” and the location in memory that the class itself is stored “0x0332DB.” We’ve successfully created an instance of the Car object and stored it into our “ford” variable.
Creating Multiple Instances
Remember that you can create as many instances as you want from each class; however, you store them in separate variables or data collections. Let’s create two instances from our class:
# instantiating multiple objects from the same class class Car( ): pass ford = Car( ) subaru = Car( ) # creates another object from the car class print( hash(ford) )
print( hash(subaru) ) # hash outputs a numerical representation of the location in memory for the variable
Go ahead and run the cell. When we output the hash values for our variables, we get two different numbers. These numbers are a numerical representation of the variables’ location in memory. Meaning that although the two variables are created from the same source, they are stored as separate entities within the program. This is the beauty of objects, as each instance can have personal characteristics.
Do'stlaringiz bilan baham: |