Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Object ใน Python คืออะไร อธิบายพร้อมตัวอย่าง

Object ใน Python คืออะไร?

Python เป็นภาษา Object-Oriented Programming (OOP) เกือบทุกอย่างใน Python ถือเป็น Object Object มี Properties (Attributes) และ Behaviors (Methods) ของตัวเอง

Class คืออะไร?

Class เป็น Blueprint (แม่แบบ) ของ Object หรือเรียกว่า Object Constructor สำหรับสร้าง Object หนึ่ง Class สร้าง Object ได้หลายตัว และค่า Properties ของแต่ละ Object อาจต่างกันได้

ตัวอย่าง Properties และ Behaviors ของ Object

ยกตัวอย่าง รถยนต์ (Car) เป็น Object:

  • Properties: สี, ยี่ห้อ, ปีผลิต, ราคา, ไมล์เลข
  • Behaviors: เพิ่มความเร็ว, ลดความเร็ว, เบรก, เปิด/ปิดเครื่อง
Object เชื่อมโยงสิ่งต่างๆ กับวัตถุจริงในชีวิต ทุกอย่างรอบตัวเรามี Properties และ Functions ของตัวเอง

ตัวอย่าง Class และ Object

Class Person มี Properties: name, age, gender ทุกคนเป็น Object ของ Class Person แต่แต่ละคนมีค่า Properties ต่างกัน

Instantiation คืออะไร?

Object เรียกอีกอย่างว่า Instance ของ Class กระบวนการสร้าง Object จาก Class เรียกว่า Instantiation

การกำหนด Class ใน Python

ใช้ Keyword class (เหมือน Function ใช้ def) ภายใน Class จะประกาศ Attributes และ Methods ที่ร่วมกัน Object ที่สร้างจาก Class จะเข้าถึง Properties และ Functions เหล่านี้ได้ แต่ละ Object จะเก็บค่า Properties ของตัวเอง

การสร้าง Object ใน Python

object_name = ClassName()

ตัวอย่างโค้ดสมบูรณ์

class Person:
    # Class Attributes (Shared by all instances)
    species = "Human"
    
    def __init__(self, name, age, city):
        # Instance Attributes (Unique per object)
        self.name = name
        self.age = age
        self.city = city
    
    def display(self):
        print(f"Name : {self.name}")
        print(f"Age  : {self.age}")
        print(f"City : {self.city}")
    
    def greet(self):
        print(f"Hello, I'm {self.name} from {self.city}")

# สร้าง Object (Instantiation)
p1 = Person("Rahul", 20, "Kolkata")
p2 = Person("Karan", 22, "Bangalore")

# เรียกใช้ Methods
p1.display()
print()
p2.display()
print()
p1.greet()
p2.greet()

# เข้าถึง Attributes โดยตรง
print(f"\n{p1.name} is {p1.age} years old")
print(f"{p2.name} is {p2.age} years old")

# Class Attribute
print(f"\nSpecies: {Person.species}")
print(f"p1 species: {p1.species}")
print(f"p2 species: {p2.species}")

ผลลัพธ์

Name : Rahul
Age  : 20
City : Kolkata

Name : Karan
Age  : 22
City : Bangalore

Hello, I'm Rahul from Kolkata
Hello, I'm Karan from Bangalore

Rahul is 20 years old
Karan is 22 years old

Species: Human
p1 species: Human
p2 species: Human

แนวคิดสำคัญ

  • __init__: Constructor เรียกอัตโนมตตอนสร้าง Object
  • self: อ้างอิง Instance ปัจจุบัน (เหมือน this ในภาษาอื่น)
  • Instance Attributes: เฉพาะ Object นั้นๆ (self.name, self.age)
  • Class Attributes: ร่วมกันทุก Object (Person.species)
  • Methods: Functions ภายใน Class รับ self เป็น Parameter แรก