เมื่อจำเป็นต้องสร้างคลาสที่มีวิธีการที่ยอมรับสตริงจากผู้ใช้ และวิธีอื่นที่พิมพ์สตริง จะใช้วิธีเชิงวัตถุ ที่นี่ คลาสถูกกำหนด และแอตทริบิวต์ถูกกำหนด ฟังก์ชั่นถูกกำหนดไว้ภายในคลาสที่ดำเนินการบางอย่าง มีการสร้างอินสแตนซ์ของคลาสและฟังก์ชันต่างๆ จะถูกใช้เพื่อดำเนินการกับเครื่องคิดเลข
ด้านล่างนี้เป็นการสาธิตสำหรับสิ่งเดียวกัน -
ตัวอย่าง
class print_it():
def __init__(self):
self.string = ""
def get_data(self):
self.string=input("Enter the string : ")
def put_data(self):
print("The string is:")
print(self.string)
print("An object of the class is being created")
my_instance = print_it()
print("The 'get_data' method is being called")
my_instance.get_data()
print("The 'put_data' method is being called")
my_instance.put_data() ผลลัพธ์
An object of the class is being created The 'get_data' method is being called Enter the string : janewill The 'put_data' method is being called The string is: janewill
คำอธิบาย
- มีการกำหนดคลาสชื่อ 'print_it' ซึ่งมีฟังก์ชันเช่น 'get_data' และ 'put_data'
- ใช้เพื่อดำเนินการต่างๆ เช่น รับข้อมูลจากผู้ใช้และแสดงบนหน้าจอตามลำดับ
- อินสแตนซ์ของคลาสนี้ถูกสร้างขึ้น
- ค่าสำหรับสตริงถูกป้อน และดำเนินการกับค่านั้น
- ข้อความและเอาต์พุตที่เกี่ยวข้องจะแสดงบนคอนโซล