#describing the rectangle
rectangle.describe("A wide rectangle, more than twice\
as wide as it is tall")
#making the rectangle 50% smaller
rectangle.scaleSize(0.5)
#re-printing the new area of the rectangle
print rectangle.area()
As you see, where self would be used from within the class instance, its assigned name is used when outside the class. We do this to view and change the variables inside the class, and to access the functions that are there.
We aren't limited to a single instance of a class - we could have as many instances as we like. I could do this:
Code Example 5 - More than one instance
longrectangle = Shape(120,10)
fatrectangle = Shape(130,120)
and both longrectangle and fatrectangle have their own functions and variables contained inside them - they are totally independent of each other. There is no limit to the number of instances I could create.
Lingo
Object-oriented-programming has a set of lingo that is associated with it. Its about time that we have this all cleared up:
* When we first describe a class, we are defining it (like with functions)
* The ability to group similar functions and variables together is called encapsulation
* The word 'class' can be used when describing the code where the class is defined (like how a function is defined), and it can also refer to an instance of that class - this can get confusing, so make sure you know in which form we are talking about classes
* A variable inside a class is known as an Attribute
* A function inside a class is known as a method
* A class is in the same category of things as variables, lists, dictionaries, etc. That is, they are objects
* A class is known as a 'data structure' - it holds data, and the methods to process that data.
Inheritance
Lets have a look back at the introduction. We know how classes group together variables and functions, known as attributes and methods, so that both the data and the code to process it is in the same spot. We can create any number of instances of that class, so that we don't have to write new code for every new object we create. But what about adding extra features to our golf club design? This is where inheritance comes into play.
Python makes inheritance really easily. We define a new class, based on another, 'parent' class. Our new class brings everything over from the parent, and we can also add other things to it. If any new attributes or methods have the same name as an attribute or method in our parent class, it is used instead of the parent one. Remember the Shape class?
Code Example 6 - the Shape class
class Shape:
def __init__(self,x,y):
self.x = x
self.y = y
description = "This shape has not been described yet"
author = "Nobody has claimed to make this shape yet"
def area(self):
return self.x * self.y
python tutorials
Start from the beginning
