Python is an object-oriented programming language. What this means is that almost everything is an object. An object in Python is a collection of attributes that collectively describe a "thing". That "thing" can be anything you want: a book, an animal, a movie.
To create an object, we must first define a class.
Creating a class is simply defining the blueprint that will be used by all subsequent objects. To define a class, use the
class keyword, and define the data points inside.
class Person: name = "Barack Obama"
That's it, we've defined a class, called
Person and it contains a property named
name which is set to
Now that we have our class defined, let's create a Barack Obama!
To create a new object, simply reference the class you want to build the object out of. In this case, we'll use our previously defined
class Person: name = "Barack Obama" person = Person() print(person.name)
Awesome, we created a new person and printed out the name by accessing the property directly. This is cool and all, but now let's make our classes useful.
You can pass in parameters to the object creation process similar to how you can pass in paramters to functions. You do this by defining a constructor for your class that can initialize your new object using parameters that you pass in.
Let's allow the name of the person to be customizable by using the built-in
class Person: def __init__(self, name): self.name = name person = Person("Ash Ketchum") print(person.name)
Since classes are just blueprints for objects, you can also create multiple objects using the same class:
class Person: def __init__(self, name): self.name = name person1 = Person("Ash Ketchum") person2 = Person("Brock Harrison") print(person1.name) print(person2.name)
Ash Ketchum Brock Harrison
You can also change an object's property directly:
class Person: def __init__(self, name): self.name = name person1 = Person("Ash Ketchum") print(person1.name) person1.name = "Misty Williams" print(person1.name)
Ash Ketchum Misty Williams
self keyword is used to refer to the current object being created. Hence when the constructor is called (which happens automatically), it is setting the new object's properties using the parameters you passed in.
Strings and numbers aren't the only thing you can define in classes. Objects can also contain functions. Let's create one in our
class Person: def __init__(self, name): self.name = name def introduction(self): print("Hi, my name is " + self.name) person1 = Person("Ash Ketchum") person2 = Person("Brock Harrison") person1.introduction() person2.introduction()
Hi, my name is Ash Ketchum Hi, my name is Brock Harrison