Overview
A class is a logical grouping, this can be variables, functions (called methods when in a class) and other classes (subclasses). This approach is called object orientated programming. This is a very brief example of creating a class and using them.Example
If we want to create an object (a class) that holds the information we want to associate with a customer.1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | class customer (object): def __init__(self, name = "", balance = 0, numberOfTransations = 0, discount = 0): self.name = name self.balance = 0 self.numberOfTransations = 0 self.discount = 0 def credit(self, amount): self.numberOfTransations += 1 self.balance = self.balance + amount def purchase(self, amount): self.numberOfTransations += 1 self.balance = self.balance - amount dean = customer() print (dean.balance) print (dean.numberOfTransations) print (dean.discount) dean.credit(45) print (dean.balance) dean.purchase(10) print (dean.balance) print (dean.numberOfTransations) print (dean.discount) owen = customer() owen.balance = 200 print (owen.balance) |
1 2 3 4 5 6 7 8 | 0 0 0 45 35 2 0 200 |
We create a blueprint for the object we want when we create the class.
def __init__(self) - this is a special functions that is automatically executed when the class is created.
Related Sections
Python - Learn the python from the basics up. This fast track example code course will get you creating powerful python programs in no time.Tkinter - Learn the key features of the tkinter to allow you to create user interfaces for your python programs.
Related Pages
Pickle - The pickle library allows a program to save data in a binary file.Python - List Comprehension - Create powerful list comprehension expressions.
Python - Generators - Learn about generator statements.
Python - Data types - The learn about the key datatypes in the python language.
Tkinter - Combo Box - This is a short example showing how to use combo boxes in a GUI.
Tkinter - Radio Buttons - A short example of how to create a GUI with radio buttons.
Tkinter - Canvas - Canvas allows for a range of shapes to be plotted, such as circles, squares, lines