Popular Posts

Thursday, February 9, 2023

Understanding Python Class

Hello, Developer!


Today, I will exercise about Python 'Class'.

Class is based on OOP(Objective Oriented Programming) and I need to exercise it with several examples about class for clear understanding.


Did you remember about 'Class'?

It consists of two parts - Data and Function as following image. Normally, developers call 'data' in class as 'attribute' and 'function' in class as 'method'.

You can create a class with following construct.

class Class_Name:
    data
    function(method)

Example

class MyClass():
 Color = Green                Data(Attribute) part
 def painting(self):            Function(Method) part
      paint(shape)

You can created a object(=instance) from class as following.

paint_shape = MyClass()      Create 'paint_shape' object from the 'MyClass' class

You can use a function in the created object(=instance) as following.

paint_shape.painting()         Call painting function(method) from paint_shape object.

You can inherit from parent classes(father & mother). 

If you create a Child class and inherits Class Father & class Mother, Child instance can use data and methods of Father and Mother classes.

Let's see following example.

Class father has attribute "hard" and method "work"
Class mother has attribute "kind" and method "cook"
Calss child inherits Father and Mother classes and has own method "sleep"

'child' class can use "work" method from 'father' class and use "cook" method from 'mpther' class and use its own "sleep" method.

You can easily inherit from other classes by adding class names in class definition line as following.

Class inherite example 
 
class child(father, mother):       # 'child' class inherits 'father' class 'mother' class

This is how classes work in Python. Let's study more about class together!

No comments:

Post a Comment

Python - Web crawling exercises

Hello Python developer! How are you? Hope you've been good and had wonderful time with Python. There are 10 Python requests module exerc...