Creating an object (instance)
Related code
class Dog: """Represents a dog."""
To make a real dog from our Dog
class (called an instance or object),
we write the name of the class, followed by open and close parentheses:
... murki = Dog()
This creates a Dog
instance and saves it in the variable murki
.
... murki = Dog() print(murki)
<__main__.Dog object at 0x7f84b0fca5e0>
That's just Python telling us:
"This is a Dog object stored in memory with 0x7f84b0fca5e0
reference."
Exercises
Create a class that represents laptop, create one instance of it, save it to a variable, and print it.
class Person: """Represents a person.""" class Human: """Represents a human.""" p = Person()
Given the above script
How many classes are defined: | |
How many objects are created: | |
What class does the object p belong to: |
Exercises
Create a class named Hen
Create a hen and assign it to hen1
Print hen1
Create a class named Teacher
Create a hen and assign it to tch
Print tch
Create a class that represents airplanes
Create two airplanes and assign them to air1 and air2
Print air1 and air2
Create two classes, one that represents a phone, the other that represents a game.
Create one phone and one game and assign them to two variables
Print the phone and the game
Create a class that represents user, create one instance of it, save it to a variable, and print it
class Owl: """Represents an owl.""" huti = Owl() bufi = Owl()
Given the above script
How many classes are defined: | |
How many objects are created: | |
What class does the object huti belong to: | |
What class does the object bufi belong to: |