Wednesday, April 17, 2024

Python Tutorial - Polymorphism - 019

 Polymorphism adalah konsep yang fundamental dalam object-oriented programming.  Kata Polymorphism merujuk pada classes yang berbeda yang diperlakukan sebagai class yang sama melalui inheritance.


Image - Polymorphism (credit to CodersArcade)

Syntax Error:
Class Bear:
def sound(self):
print("Groarrr") class Dog:
def sound(self):
print("Woof woof!") def makeSound(animalType):
animalType.sound()

bearObj = Bear()
dogObj = Dog()

makeSound(bearObj)
makeSound(dogObj)


True Correction:
class Bear: def sound(self): print("Groarrr") class Dog: def sound(self): print("Woof woof!") def makeSound(animal): animal.sound() bearObj = Bear() dogObj = Dog() makeSound(bearObj) makeSound(dogObj)

Output:
Groarrr
Woof woof!

In Python, indentation is crucial for defining code blocks. Here's a breakdown of the corrected code:
Classes:
  • We define two classes, Bear and Dog, each having a sound method.
  • The sound method prints the corresponding animal sound ("Groarrr" for bear and "Woof woof!" for dog).
makeSound function:
  • This function takes an animalType argument as input.
  • Inside the function, we call the sound method of the animalType object to produce the sound.
Creating objects and calling functions:
  • We create instances (bearObj and dogObj) of the Bear and Dog classes, respectively.
  • Then, we call the makeSound function twice, passing bearObj and dogObj as arguments. This invokes the corresponding sound methods for each object.

class Bear: def sound(self): print("Groarrr")

class Dog:
def sound(self):
print("Woof woof!")

def makeSound(animalType):
animalType.sound()
    print("Groarrr")

bearObj = Bear()
dogObj = Dog()

makeSound(bearObj)
makeSound(dogObj)

"When creating applications like a document editor, you may not know beforehand the types of documents a user will open, be it PDF or Word. Rather than having separate types for each document format, wouldn’t it be convenient to access them uniformly?"
"By defining an abstract class, we can outline a structure that every derived class must adhere to. Here’s how it works:"
class Document:
def __init__(self, name):
self.name = name
def show(self):
raise NotImplementedError("Subclass must implement this abstract method")
==========================

Dalam Python, Polymorphism diekskusi dengan berbagai cara, termasuk menggunakan functions dan abstract classes.


Function-Based Polymorphism in Python
    Semisal, ada dua classes, yaitu: Bear and Dog. Setiap class ini punya sebuah metode yang menghasilkan bunyi unik. 
    Menggunakan Polymorphism, kita bisa menggunakan metode sound untuk object  class ini melalui function umum.

SyntaxError:  
class Bear(object):
    def sound(self):
        print("Groarrr")

        class Dog(object):
    def sound(self):
        print("Woof woof!")

        def makeSound(animalType):
    animalType.sound()

    bearObj = Bear()
dogObj = Dog()

makeSound(bearObj)
makeSound(dogObj)

Correction program:



Error and true
class Bear(object):
    def sound(self):
        print("Groarrr")
class Bear:
def sound(self):
    print("Groarrr")

 class Dog(object):
    def sound(self):
        print("Woof woof!")

        def makeSound(animalType):
    animalType.sound()

bearObj = Bear()
dogObj = Dog()

makeSound(bearObj)
makeSound(dogObj)
--------------------------------------------

Abstract Class-Based Polymorphism




class Document: def __init__(self, name): self.name = name def show(self): raise NotImplementedError("Subclass must implement this abstract method")

class Pdf(Document): def show(self): return 'Show pdf contents!' class Word(Document): def show(self): return 'Show word contents!' documents = [Pdf('Document1'), Pdf('Document2'), Word('Document3')] for document in documents: print(document.name + ': ' + document.show())

Output:
Document1: Show pdf contents!
Document2: Show pdf contents!
Document3: Show word contents!'
# Posting sebelumnya:
JJJ

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

Wednesday, April 10, 2024

Python Tutorial - Metode Overloading - 017

Ada banyak cara untuk mendifinisikan dan meyebut metode (fnction) dalam bahasa rogram Python.  



Image - Hanya ilustrasi saja, tanda dilarang parkir.

Tergantung pada mendifinisikan function, bisa didefinisikan dengan "zero, one, two or more parameters."

Hal ini disebut dengan istilah "method overloading," tak banyak program bisa melakukan hal ini.


Contoh Metode Overloading
Class dengan satu metode(fungsi) adalah sayHello().
- parameter metode adalah None
- object dikreasi berdasarkan class
class Human:
    def sayHello(self, name=None):
        if name is not None:
            print('Hello' + name)
        else:
            print('Hello')

obj = Human()
obj.sayHello()
obj.sayHello('Guido')

Output (ekskusi dengan main.pay)
Hello
HelloGuido

# Posting sebelumnya:

JJJJJJJJJJJJ

Monday, April 8, 2024

Python Tutorial - Encapsulation - 016

 Encapsulation adalah konsep dasar dalam Object Oriented Programming (OOP).  Encapsulation menyebabkan kita bisa melakuan restriksi. 



Image - Ilustrasi saja, order secara digital.

Restriksi itu dilakukan terhadap metode dan variabel tertentu dalam class.

Apa itu "Object-Oriented Programming?":
- OOP tergantung pada konsep classes dan objects
- Classes mendifinisikan attributes dan metode
- objects dikreasi dari classes
- Untuk contoh, ada class yang disebut car. Attributesnya color, brand dan mode. Kemudian myCar adalah nilai unik dari class.


Memahami Private Method
Kita punya car sebagai class, dimana ada main method, yaitu main method: drive() dan private method: _udateSoftware().
class Car:
    def __init__(self):
        self.__updateSoftware()
    def drive(self):
        print('driving')
    def __updateSoftware(self):
        print('updating software')

redcar = Car()
redcar.drive()

Output:
updating software
driving


Memanfaatkan Private Variabel.
class Car:
    __maxspeed = 0
    __name = ""
    def __init__(self):
        self.__maxspeed = 200
        self.__name = "Supercar"
    def drive(self):
        print('driving. maxspeed ' + str(self.__maxspeed))

redcar = Car()
redcar.drive()
redcar.__maxspeed = 10  # This won't alter the variable as it's private.
redcar.drive()

Output:
driving. maxspeed 200
driving. maxspeed 200


Sekarang kita ingin mengubah private variabel:
class Car:
    __maxspeed = 0
    __name = ""
    def __init__(self):
        self.__maxspeed = 200
        self.__name = "Supercar"
    def drive(self):
        print('driving. maxspeed ' + str(self.__maxspeed))
    def setMaxSpeed(self, speed):
        self.__maxspeed = speed

redcar = Car()
redcar.drive()
redcar.setMaxSpeed(320)
redcar.drive()

Output:
driving. maxspeed 200
driving. maxspeed 320

# Posting sebelumnya:

JJJJJJJJJJJJJJJJ

Sunday, April 7, 2024

Python Tutorial - Classes and object - 015

Dalam memahami Python, kita berhadapan dengan konsep "classes." Mari kita mulai asal mula dari mana asal usul classes.  


Image - Bunga liar, hanya ilustrasi.

Ada hal hal penting untuk memahami classes.
1) Statements
ogrammer hanya menulis perintah atau statements untuk berkomunikasi dengan mesin.

2) Fungsi
Dipakai agar "code" lebih modular dan bisa dibaca. Ini adalah grup statements agar code lebih baik.

3) Classes dan Objects.
Jantung dari Object Oriented Programming (OOP) adalah classes. Dengan classes kita menghasilkan Objects.

Objects di sini memiliki dua hal, yaitu: Fungsi (methods) dan Variables. Contoh:
- String variabel bernama 'book' memiliki metode seperti: book.replace() dan book.lower().
- paradigma program ini adalah model real world objects yang disebut "object-oriented programming"


Memahami Classes Dalam Python
Classes menyebabkan kita bisa membuat virtual objects. Objects itu bisa mengandung baik variables (attributes) dan fungsi (methods). Contoh:
Class User:
    name = " "
    def _init_ (self, nme):
         self.name = name

        def sayHello(self):
             print("Hello, my name is " + self.name)

Dalam hal ini:
- User adalah class dengan atribute (variabel) name dan method (function) sayHello.

Class yang kita buat adalah:
james = User("James")
david = User("David")
eric = User("Eric")
------------------------------------------------------

Contoh yang sudah dieksusi akai "main.py":
class User:
    def __init__(self, name):
        self.name = name

    def sayHello(self):
        print("Hello, my name is " + self.name)

# Example usage:
eric = User("Eric")
eric.sayHello()

Output: Hello, my name is Eric
----------------------------------------------------------------

Contoh lain yang sudah diekskusi pakai "main.py"
class Animal:
    def __init__(self,name):
        self.name = name

    def walk(self):
        print(self.name + ' walks.')

duck = Animal('Duck'
duck.walk()

Output: Duck walks.

# Posting sebelumnya:


JJJJJJJJJJJJ


JJJJJJJJJJJJ

Python Tutorial - Writing File - 014

 Kita sudah tahu tetang "reading file," sekarang kita akan memahami writing file dalam Python. 


Image - Grocery di desa

3 hal penting dalam python berkenaan dengan file:
1) Opening file
- memakai fungsi: open(filename, 'w'). Di sini, filename bisa actual file atau file path 
"A file path is a string that specifies the location of a file or directory within a file system."
"An actual file refers to the physical data stored on disk or other storage media. It represents the content and metadata associated with a file."

2) Writing Data.
Setelah opening, kita bisa menggunakan: .write() untuk melakuan input terhadap content yang kita ingini.

3) Closing file.
Jangan lupa melakukan closing file.


Membuat atau Overwriting File dalam Python
filename = "newfile.txt"
myfile = open(filename, 'w')
myfile.write('written with Python\n')
myfile.close()


Appending untuk file yang sudah exist.
filename = "newfile.txt"
myfile = open(filename, 'a')
myfile.write('Appended with Python\n')
myfile.close()

# Posting sebelumnya:

Friday, April 5, 2024

Python Tutorial - Reading File - 013

Memahami File adalah hal penting untuk seorang programmer Python. Ada beberapa metode untuk membaca File dengan Python.


Image - Hanya ilustrasi

Singkatan penting:
  • Read Only (‘r’)
  • Read and Write (‘r+’)
  • Write Only (‘w’)
  • Write and Read (‘w+’)
  • Append Only (‘a’)
  • Append and Read (‘a+’)

Cara yang umum untuk membaca file (reading file) adalah menggunakan fungsi "open()"


Membaca File dalam String.
f = open("file.txt", "r")
lines = f.readlines()
print(lines)

# Posting sebelumnya:

Saturday, March 30, 2024

Python Tutorial - Angka Random - 012

Hal umum. Python melakukan generating untuk data data random, apakah itu untuk tujuan simulasi, testing dan gaming. 


Image - Ayam Turkey salai

Fungsi "random()" menghasilkan angka diantara 0 dan 1, seperti [0, 0.1 .... 1].

Generating a random float antara 0 dan 1
from random import random
print(random())
output: 0.332587482267

Angka integer antara 1 dan 100
from random import randint
print(randint(1, 100))
Output : 55

Storing Integer di variabel
from random import randint
number = randint(1, 100)
print(number)
Output: 26


Angka Random Float antara 1 dan 10
Kita bisa memakai Fungsi "uniform()"
from random import uniform
print(uniform(1, 10))
Output : 9.7811


Manipulasi Lists dengan Randomness
from random import shuffle
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
shuffle(numbers)
print(numbers)
Output: [5, 1, 4, 10, 7, 9, 6, 3, 8, 2]


Menyeleksi Hal Random dari List
from random import sample
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
single_item = sample(numbers, 1)[0]
print(single_item)
Output: 8

multiple_items = sample(numbers, 4)
print(multiple_items)
[7, 5, 10, 4]



Lists mengandung Strings
from random import sample
names = ['Alissa', 'Alice', 'Marco', 'Melissa', 'Sandra', 'Steve']
single_name = sample(names, 1)[0]  # Picks one random name from the list.
print(single_name)
Output: Alissa

multiple_names = sample(names, 4)
print(multiple_names)
Output: ['Alice', 'Marco', 'Steve', 'Melissa']

# Posting sebelumnya:

JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJ

Friday, March 29, 2024

Python Tutorial - Casting - 011

Bahasa Python bisa mengenal type type data apakah itu type data integer atau string secara otomatis. 


Image - Hanya Ilustrasi saja

Hanya contoh: x = 3 adalah intiger, sedangkan y = "text" adalah string. 

Casting Data
x = 3
y = 2.153

Print("We have defined two numbers")
print("x = " + str (x))....>wrong
print("y = " + str (y))....> Wrong
Output: error

Correction of program
Print("We have defined two numbers")
print("x = ", x)
print("y = ", y)
Output:
We have defined two numbers
('x =', 3)
('y =', 2.153)

# Posting sebelumnya:

JJJJJJJJJJJJJJJJJJJ

Monday, March 25, 2024

Data Engineering - Microsoft Certificates

"Data engineers focus on designing, building, and maintaining data pipelines and infrastructure. They ensure that data is collected, processed, and made available for analysis."


Image 01 - Data Engineering (credit: Google)

Skills Needed:
- Proficiency in programming languages (e.g., Python, Java, Scala).
- Knowledge of databases (SQL and NoSQL).
- Experience with cloud platforms (e.g., Azure, AWS, Google Cloud).
- Understanding of data modeling, ETL (Extract, Transform, Load) processes, and data warehousing.

Common tools for extraction include SQL queries, custom scripts, and ETL tools like Apache NiFi, Talend, or Informatica.



Image 02 - Goreng ikan, ilustrasi


JJJJJJJ