: Please somebody help. I am picking up python reasonably quickly, but going over certain tutorials again and again I just can't grasp the concept of classes. Can somebody please explain how to use them and what they do as if addressing a monkey, because I'm just banging my head against a wall!
: Also, and feel free to laugh, but I can't understand exactly what is meant by an 'object'.
Classes and Objects aren't just for Python, these are basic object-oriented programming (OOP) concepts.
An object is any 'thing'. A box in an object. A door is an object. In the case of Python and many other languages, strings, integers, files, etc are all objects.
A class is what you might call the "type" or "kind" of an object. Some people like to think of a class as the blueprints and objects as the things created from the blueprints. You could use the same set of blueprints to build a dozen houses. Each house is a distinct thing, but they are all of the same class.
In Python terms, the object "FOOBAR" is an instance of a string class. 1 is an instance of an integer class.
Classes serve to encapsulate data with the functionality that manipulates that data.
def __init__(self, length, width):
self.length = length
self.width = width
return self.length * self.width
This class statement creates the blueprints for creating objects of type "Rectangle".
r1 = Rectangle(5, 10)
r2 = Rectangle(2, 3)
The above code uses the Rectangle class to create two objects, r1 and r2. To get the area of r1, we would call r1.area(). r1 and r2 are said to be "instances of class Rectangle". They are distinct objects with their own identities even though they are the same kind
When one kind of thing is a specialized version of some other thing, you can inherit the traits of the more general thing and extend it with only the new features. For example, all squares are special kinds of rectangles. We could create the following class:
def __init__(self, length):
self.length = length
self.width = length
Now we can create instances of the Square class. Note that we pass only one dimension:
s1 = Square(4)
s2 = Square(5)
Both of these objects inherit
the area() function from the Rectangle class because the math works the same way for both Rectangles and Squares.
Let me know if you're still confused.
$ select * from users where clue > 0
no rows returned