Hello, Developer!
Hope you're good at handling modules in the Python.
Today, we will learn the "Classes & Objects".
Python is an object-oriented programming language. Class is an object constructor and we can create data types as objects modeling the real world.
For creating an object, we have to define a class first. Because objects can be created from classes.
In the class, "__init__()" function is used for assigning values to each property in objects. Also, we can define functions in the class
Class Form
class sample_class: # Define class with class name(i.e. sample_class)
def __init__(self, value_1, value_2): # Define initiated class values
self.value_1 = name # Define value matches class value
self.value_2 = age
def class_function(self): # Define function in the class
print("This is class exercise!")
Object Form
object_1 = sample_class("Class", "No.1") # Create object with modeling class with values
object_1.class_function() # Using class function
I showed full class & object exercise codes as following.
Class(Student_class.py)
class Student:
def __init__(self, name, major, gpa, is_on_probation):
self.name = name
self.major = major
self.gpa = gpa
self.is_on_probation = is_on_probation
def print_func(self):
print("This student's name is : " + self.name)
Class & Objects.py
from Student_class import Student # From Student_class file import Student class
student01 = Student("Jim", "Business", 3.1, False)
student02 = Student("Alex", "Sales", 3.5, True)
print(student01.gpa)
print(student02.major)
student01.print_func()
student02.print_func()
Exercise Result
Can you see the same result on your PC? Great job! You can create class & object in Python and you started the object-oriented programming!
See you at the next post, Python developer! 😊
No comments:
Post a Comment