Basic_Python_6
Basic_Python_6
Object
Class and
Object
Page 01
Content
Class Object
Page 02
Python: Classes
Create a Class
To create a class, use the keyword class:
Create a class named MyClass, with a property named x:
class MyClass:
x=5
Page 03
Python: Objects
Create Object
Now we can use the class named MyClass to create objects:
Page 04
Python: The __init__() Function
The examples before are classes and objects in their simplest form, and are not really
useful in real life applications.
All classes have a function called __init__(), which is always executed when the class is
being initiated.
Page 05
Python: The __init__() Function
Use the __init__() function to assign values to object properties, or other operations that
are necessary to do when the object is being created:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
Page 06
Python: Object Methods
Objects can also contain methods. Methods in objects are functions that belong to the
object.
Insert a function that prints a greeting, and execute it on the p1 object:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc()
Page 07
Quiz Session
Page 08
Quiz
def greet(self):
print(“Hello”)
print(Person.age)
print(Person.greet)
print(Person.__doc__)
Page 09
Terima Kasih!
Indonesia AI | AI for Everyone, AI for Indonesia
contact@aiforindonesia.org