Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1
method performs an operation, using the attributes in a class. For instance, you could create
class methods to retrieve a specific person from a database, or change the address attribute for
an existing person. Each method should be contained within a class and perform operations only
in that class. The methods for one class shouldn’t deal with attributes in other classes.

Defining a Class


Defining a class in Python isn’t too much different from defining a function. To define a new class,
you use the class keyword, along with the class name, and a colon, followed by any statements
contained in the class. Here’s an example of a simple class definition:


>>> class Product:
pass

>>>

The class name you choose must be unique within your program. And while it’s not required, it’s
somewhat of a de facto standard in Python to start a class name with an uppercase letter.


The statements section for the class defines any attributes and methods that the class contains. Just as
with functions, you must indent the class statements in the code. When you’re done defining the class
attributes and methods, you just place the next code statement on the left margin.


The pass statement shown in this example is special in Python. It’s a statement that does nothing!
You normally use the pass statement as a placeholder for code that you’ll add in the future. In this
example, the pass statement creates an empty class definition. You can use the class in your Python
code, but it won’t do anything!


Creating an Instance


The class definition defines the class, but it doesn’t put the class to use. To use a class, you have to
instantiate it. When you instantiate a class, you create what’s called an instance of the class in your
program. Each instance represents one occurrence of the object. To instantiate an object, you just call
it by name, like this:


>>> prod1= Product()
>>>

The prod1 variable is now an instance of the Product class. After you create an instance of a
class, you can define attributes “on the fly,” as shown here:


Click here to view code image


>>> prod1.description = 'carrot'
>>> print(prod1.description)
carrot
>>>

Each instance is a separate object in Python. If you create a second instance of the Product class,
the attributes you define in that instance are separate from the attributes you define in the first
instance, as shown in this example:


Click here to view code image


>>> prod2 = Product()
>>> prod2.description = "eggplant"
>>> print(prod2.description)
Free download pdf