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

โปรแกรม Python สร้างคลาสรับสตริงและพิมพ์สตริง


เมื่อต้องการสร้างคลาสที่มีเมธอดรับสตริงจากผู้ใช้ และอีกเมธอดพิมพ์สตริง ใช้วิธี Object-Oriented กำหนดคลาสและแอตทริบิวต์ กำหนดฟังก์ชันภายในคลาสที่ดำเนินการบางอย่าง สร้างอินสแตนซ์ของคลาส และใช้ฟังก์ชันดำเนินการ

ตัวอย่าง

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'
  • ใช้ดำเนินการรับข้อมูลจากผู้ใช้และแสดงบนหน้าจอตามลำดับ
  • สร้างอินสแตนซ์ของคลาสนี้
  • ป้อนค่าสำหรับสตริง และดำเนินการ
  • แสดงข้อความและเอาต์พุทที่เกี่ยวข้องบนคอนโซล