Thursday, April 11, 2024

Python Tutorial - Class Inheritance - 018

Python menawarkan paradigma kuat dalam "Object-Oriented Programming," sehingga class bisa "diwariskan" fungsi dari Class lainnya. 


Image - Class Inheritance (credit to Google).

"This enables objects that are created using a class inheriting from a superclass to have access to methods and variables of both the superclass and the derived class. Unlike some other languages, Python even supports multiple inheritance, expanding its utility."

Understand Class name User:
class User:
    name = ""
    
    def __init__(self, name):
        self.name = name

    def printName(self):
    print("Name = " + self.name)

brian = User("brian")
brian.printName()
Note: program error

Yang benar:
class User:
    def __init__(self, name):
        self.name = name

    def printName(self):
        print("Name = " + self.name)

brian = User("brian")
brian.printName()
=============================================
Mari Kita disain class yang lain, yaitu Programmer
class Programmer(User):
    def __init__(self, name):
        self.name = name

    def doPython(self):
        print("Programming Python")


Now, we do comprehensive inheritance 
class User:
    def __init__(self, name):
        self.name = name
    
    def printName(self):
        print("Name = " + self.name)

class Programmer(User):
    def doPython(self):
        print("Programming Python")

brian = User("Brian")
brian.printName()

diana = Programmer("Diana")
diana.printName()
diana.doPython()

Output: 
Name = Brian
Name = Diana
Programming Python

# Posting sebelumnya:

JJJJJJJJJJ
JJJJJ

No comments:

Post a Comment