Hey guys, this marks my second post on the Forums.

I recently asked about the def statement and the import statement. After that being answered I wanted to ask another question and thought best to start another thread.

What is a class? What does it do and how does it differ to the def statement.

Thanks for your time, I hope someone can help me out

To understand classes, you need to know both the conceptual meaning and their concrete implementation. Abstractly, a class is a description of a type, for example, the class Animal would describe the properties which all animals have. The class acts as a template for creating objects of it's type. A class describes both the state of a given Animal, and the behaviors it is capable of.

A class may have sub-classes; for example, Animal might have the subcategory Carnivore, which in turn might have the subclasses Canine and Feline, and so on down to the particular types of animals such as Lion or Cat. It is possible for a class to be a sub-class of more than one immediate parent class; for example, a Cat is both a Feline (and hence a Carnivore, and hence an Animal), and a Pet (which is a subclass of DomesticatedAnimal, which is a subclass of Animal). Each subclass inherits the properties and behaviors of it's parent classes.

As I said, a class consists of a set of properties (called instance variables) and behaviors (called methods). These properties may in turn be members of a class. For example, a Cat has teeth, claws, and fur. Now, it is important to differentiate here between the type of something and it's properties. A Cat is a Feline (inheritance), for example, but while a Cat has claws (composition), a Cat isn't a type of claw. This may seem obvious, but it can be surprisingly difficult to get this right. The three types of relationships which classes often have - Inheritance, Composition, and Aggregation, also called 'is-a', 'has-a', and 'holds-a' relationships - are easy to get confused.

A class may represent a concrete thing - such as cats - or abstractions, such as the numbers, or lists. In fact, all the data types in Python - integers, strings, lists, tuples, dictionaries, and so forth - are actually classes.

Since no class can be exact - you can't possibly describe all of the state of a class of objects - you have to choose those properties which are relevant to your needs.

In Python, you declare a class with the keyword class followed by the class's name, it's list of immediate superclasses, and it's methods (which are declared almost the same as a function). For example,

class Animal(object):
    def __init__(self, position):
        self.position = position
    def move(self, direction, distance):
        pass
    def eat(self, food):
        pass

Now, this is just a simple example, without only one instance variable and three methods, all of which simply do nothing. It's enough to show you the structure of a class, however. Two things to know are the __init__() method, and the self variable. When you crate an instance of a class, you use the name of the class as if it were a function, and it returns an object.

myAnimal = Animal(somewhere)

The __init__() method is what is actually called when you do this; it is a special method called a constructor (often abbreviated as c'tor). The c'tor sets all of the initial state of the object as of when it is created. The other thing to know about is the self argument of each method. This is actually a reference to the object which the method is being used on. When you call a method, you write:

myAnimal.move(WEST, 20)

Note that there are only two arguments! Where is the third? Well, that's the self argument, and it's the name of the object in question, myAnimal.

Here's a more elaborate example, which I wrote for a program recently. Don't worry if it doesn't all make sense; but feel free to ask any questions you may have about it.

class Figure(object):
    def __init__(self,  type,  color):
        self.type = type
        self.color = color
        self.coordinates = list()

    def addCoordinates(self,  x,  y):
        """ Add each pair of coordinates to the list as a tuple
        """
        self.coordinates.append((x,  y))

    def __str__(self):
        s = "{0}, {1}\n".format(self.type,  self.color)
        for c in self.coordinates:
            s += '\t' + str(c) + '\n'
        return (s + '\n')

    def draw(self):
        mappings = {
                            "town": mapmaker.drawTown,
                            "ruin": mapmaker.drawRuin,
                            "cave": mapmaker.drawCave,
                            "spring": mapmaker.drawSpring
                        }
        turtle.penup()

        print("Drawing {}s".format(self.type))

        if self.type in mappings.keys():
            for pair in self.coordinates:
                mappings[self.type](pair[0],  pair[1])
        else:
            turtle.setpos(self.coordinates[0])
            turtle.pendown()
            turtle.fillcolor(mapmaker.fetchColor(self.type))
            turtle.begin_fill()
            for pair in self.coordinates[1:]:
                turtle.setpos(pair)
            turtle.end_fill()

You can also look at a class as a collection of functions/methods that belong together.
Once a class is established it can be inherited by other classes. This can save you a lot of coding.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.