Skip to content

Object Oriented Programming (OOP)

Python Logo

We need your feedback. Click here!

  • OOP can be thought of as solving problems by creating objects.

  • These objects can be compared to boxes into which we add the properties needed to describe a single part.

  • En utilisant Tkinter dans votre code, importez le package et initialisez l’objet tkinter en conséquence:

What is a class?

  • A class is a user-defined data structure in which the data format, functionality or any other property associated with the object can be defined. A class can be seen as a template for your object.
  • An object is an instance of your class. Creating your object means "making" your "concrete" drawing.
  • A class can have methods (or functions) and properties.

How do you define the class?

The code below is an example of a class definition:

class ClassName:
    # constructor
    def __init__(self, prop_one, prop_two):
        # first property
        self.prop_one = prop_one
        # second property
        self.prop_two = prop_two
    # getter for prop_one
    def get_property_one(self):
        return self.prop_one
    # setter for prop_one
    def set_property_one(self, new_prop_one):
        self.prop_one = new_prop_one
  • In this example, a class named ClassName is defined.
  • A constructor is a method that is automatically called when a class is created. This method can therefore be used to initialize all class properties when the object is created.
def __init__(self): 
    # code
  • The self keyword is the first parameter that must appear in every method defined in the class (it's called self by contract, but you can call it whatever you like). This parameter refers to the object from which any function in the class is called.

  • In ClassName, two methods are defined: get_property_one(self) and set_property_one(self, value).

  • get_property_one(self) is getta and returns the prop_one value that was initialized when the ClassName object was created.

  • set_property_one(self, new_prop_one) is defined and sets the new_prop_one value on the prop_one class.

  • How do I instantiate the ClassName?

# first instance
x = ClassName("Test", 5)
print(x.get_property_one()) # displays "Test" on your terminal
 
# second instance
y = ClassName( 5, "Test Second")
print(y.get_property_one()) # displays 5 on your terminal

Our company offers online and in-person Python training. (Register)[https://www.stuntbusiness.ca/register] now and join the community.

Références:

[1] "tkinter - Python interface to Tcl/Tk": https://docs.python.org/3/library/tkinter.html [2] "Frame": https://tkdocs.com/pyref/frame.html [3] "Canvas": https://tkdocs.com/tutorial/canvas.html