OOP Workshop
class Constructor Method
class Button:
buttonShape = "Line"
buttonColor = "Orange"
buttonX = 0
buttonY = 0
width = 100
height = 50
def __init__ (self, buttonShape, buttonColor, buttonX, buttonY, width, height):
self.buttonShape = buttonShape
self.buttonColor = buttonColor
self.buttonX = buttonX
self.buttonY = buttonY
self.width = width
self.height = height
class RectangleButton(Button):
def __init__(self, buttonColor, buttonX, buttonY, width, height):
super().__init__("Rectangle", buttonColor, buttonX, buttonY, width, height)
class TriangleButton(Button):
def __init__(self, buttonColor, buttonX, buttonY, width, height):
super().__init__("Triangle", buttonColor, buttonX, buttonY, width, height)
class CircleButton(Button):
def __init__(self, buttonColor, buttonX, buttonY, width, height):
super().__init__("Circle", buttonColor, buttonX, buttonY, width, height)
__init__ (self, ...
is a special method for initializing a class instance. The argument self
refers to the specific instance of the class being constructed. Each instance may be constructed with different values of the arguments. Each method defined as an instance method should define the self
argument as the first argument. On the other hand, when making a call to the instance methods, the self
argument is automatically provided by the python interpreter to the called method, and no explicit argument passing is necessary.
class myclass:
my_label = ""
def __init__(self, label_value):
self.my_label = label_value
def my_method(self):
print ("my_method has been called, my_label is ", self.my_label)
myclass_instance = myclass("Instance 1")
myclass_instance.my_method()
In the example above, myclass
defines an attribute my_label
which can be accessed by using the self
argument. When initializing an instance of the class myclass
, we do not provide the self
as an argument in the line myclass_instance = myclass("Instance 1")
, instead the self
argument is implicitly added by the interpreter. The same event occurs in the statement myclass_instance.my_method()
where the self
argument is implicitly set to be the myclass_instance
variable.
The class definitions
RectangleButton(Button)
,TriangleButton(Button)
, andCircleButton(Button)
are also of the type Button
as they inherit all characteristics by using the class name Button
inside a pair of ()
, extending the base (parent) class Button
.The super()
method returns the parent class reference to specifically call the methods defined in that parent class. No matter whether those methods were overridden by the child class, the implementation in the base class will be executed in such a call.