There are only a few data types in Python. All but one of them are called “primitive” data types, because their values contain only a single thing (be it a string or a number or whatever).
Python is an object oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects.
So you write "classes", and then when you run the code, Python then creates the objects to be used by the code.
Objects are used to collect and organize data - and that data can be variable values, functions and other things. Objects can also contain other objects(!), in kind of a "nesting" way. This allows for large data structures to be built using a very simple and elegant mechanism.
class Spacecraft:
name = ""
type = 'warp starship'
topspeed = 9.9We can imagine an object as a container where everything is collected about some thing in the program:
enterprise = Spacecraft()
enterprise.name = "Enterprise"
print(enterprise) # -> <__main__.Spacecraft object at 0x103013100>Which isn’t very helpful, is it? We need to create a method in our class. One that gets called whenever we want to display which spacecraft to a user.
class Spacecraft:
name = ""
type = 'warp starship'
topspeed = 9.9
def __str__(self):
return "Starship " + self.name
def speed(self):
return self.topspeed
enterprise = Spacecraft()
enterprise.name = "Enterprise"
# now when we
print(enterprise)
# we get: Starship EnterpriseThere a few things to point out in this class. First, notice how the str function is indented? It’s defined inside the class. That makes the function a method; objects have methods. You can call a method on a particular object.
enterprise = Spacecraft()
enterprise.name = "Enterprise"
constellation = Spacecraft()
constellation.name = "Constellation"
constellation.topspeed = 9.2
ets = enterprise.speed()
cts = constellation.speed()
# ets will be 9.9, cts will be 9.2This example also shows how you use a class to create multiple objects. It helps with making code simpler, and easier to follow when reading it.
There are a number of very powerful things we have left out of this discussion about Python objects. We have not covered the ideas of inheritance or the idea of subclassing. And there is much more in Python about objects. Master what we’ve written about here and then forge ahead into more complicated and powerful capabilities.
There is a lot more to learn about Python.