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

Python TypeError: object of type 'NoneType' has no len() - แก้ไข 2 กรณี

เมธอด len() ทำงานได้เฉพาะ iterable objects เช่น strings, lists, dictionaries เพราะมี sequence of values หากใช้ len() บนค่า None จะเจอ error TypeError: object of type 'NoneType' has no len()

คู่มือนี้อธิบายว่า error นี้หมายถึงอะไร ทำงานยังไง พร้อม 2 ตัวอย่าง เพื่อให้คุณแก้ในโค้ดของตัวเองได้

TypeError: object of type 'NoneType' has no len()

NoneType หมายถึง None data type ไม่สามารถใช้ methods ที่ทำงานกับ iterable objects เช่น len() บนค่า None ได้ เพราะ None ไม่มี collection of values ความยาวของ None คำนวณไม่ได้ เพราะไม่มี child values

Error นี้พบบ่อย 2 กรณี:

  • ลืมว่า built-in functions เปลี่ยน list in-place
  • ลืม return statement ใน function

มาดูแต่ละสาเหตุลึกๆ

สาเหตุ #1: Built-In Functions เปลี่ยน Lists In-Place

สร้างโปรแกรมเรียงลิสต์ dictionaries ข้อมูลนักเรียน เรียง ascending ตามเกรดสอบล่าสุด

เริ่มกำหนดลิสต์ dictionaries ข้อมูลนักเรียนและเกรด:

students = [
    {"name": "Peter", "score": 76 },
    {"name": "Richard", "score": 63 },
    {"name": "Erin", "score": 64 },
    {"name": "Miley", "score": 89 }
]

แต่ละ dictionary มี 2 keys/values: name และ score ต่อไป ใช้ sort() method เรียงลิสต์นักเรียน:

def score_sort(s):
    return s["score"]
sorted_students = students.sort(key=score_sort)

ประกาศฟังก์ชัน "score_sort" คืนค่า "score" ในแต่ละ dictionary ใช้ order items ในลิสต์ dictionaries ด้วย sort()

ต่อไป พิมพ์ความยาวลิสต์:

print("There are {} students in the list.".format(len(sorted_students)))

พิมพ์ลิสต์ dictionaries ใหม่ด้วย for loop:

for s in sorted_students:
    print("{} earned a score of {} on their last test.".format(s["name"], s["score"]))

โค้ดพิมพ์ข้อความบอกว่าแต่ละนักเรียนได้กี่คะแนน สำหรับทุกนักเรียนใน "sorted_students" รันโค้ด:

Traceback (most recent call last):
File "main.py", line 13, in 
print("There are {} students in the list.".format(len(sorted_students)))
TypeError: object of type 'NoneType' has no len()

โค้ด error

แก้ปัญหา: ต้องลบโค้ดที่ assign ผลลัพธ์ sort() ให้ "sorted_students" เพราะ sort() เปลี่ยน list in-place ไม่สร้างลิสต์ใหม่

ลบการประกาศ "sorted_students" ใช้ "students" ในโปรแกรมต่อไป:

students.sort(key=score_sort)
print("There are {} students in the list.".format(len(students)))
for s in students:
    print("{} earned a score of {} on their last test.".format(s["name"], s["score"]))

รันโค้ด:

There are 4 students in the list.
Richard earned a score of 63 on their last test.
Erin earned a score of 64 on their last test.
Peter earned a score of 76 on their last test.
Miley earned a score of 89 on their last test.

โค้ดรันสำเร็จ บอกจำนวนนักเรียน แล้วพิมพ์ข้อมูลแต่ละคนและคะแนน เรียง ascending ตามเกรด

สาเหตุ #2: ลืม Return Statement

ทำโค้ดให้ modular มากขึ้น ย้าย sorting method ไปฟังก์ชันตัวเอง กำหนดฟังก์ชันพิมพ์ข้อมูลเกรดแต่ละนักเรียน

เริ่มกำหนดลิสต์นักเรียนและ helper function score_sort (ยืมมาจากก่อนหน้า):

students = [
    {"name": "Peter", "score": 76 },
    {"name": "Richard", "score": 63 },
    {"name": "Erin", "score": 64 },
    {"name": "Miley", "score": 89 }
]
def score_sort(s):
    return s["score"]

เขียนฟังก์ชันเรียงลิสต์:

def sort_list(students):
    students.sort(key=score_sort)

กำหนดฟังก์ชันแสดงประสิทธิภาพนักเรียน:

def show_students(new_students):
    print("There are {} students in the list.".format(len(students)))
    for s in new_students:
        print("{} earned a score of {} on their last test.".format(s["name"], s["score"]))

ก่อนรัน ต้องเรียกฟังก์ชัน:

new_students = sort_list(students)
show_students(new_students)

โปรแกรมจะเรียงลิสต์ด้วย sort_list() แล้วพิมพ์ข้อมูลแต่ละนักเรียนด้วย show_students()

รันโค้ด:

Traceback (most recent call last):
File "main.py", line 21, in 
show_students(new_students)
File "main.py", line 15, in show_students
print("There are {} students in the list.".format(len(new_students)))
TypeError: object of type 'NoneType' has no len()

Error เกิดเพราะลืม "return" statement ใน "sort_list" function

ตอนเรียก sort_list() assign response ให้ "new_students" ตัวแปรนี้ส่งเข้า show_students() แก้ error: เพิ่ม return statement ใน sort_list():

def sort_list(students):
    students.sort(key=score_sort)
    return students

รันโค้ด:

There are 4 students in the list.
Richard earned a score of 63 on their last test.
Erin earned a score of 64 on their last test.
Peter earned a score of 76 on their last test.
Miley earned a score of 89 on their last test.

โค้ดคืนค่าที่คาดหวัง

สรุป

Error TypeError: object of type 'NoneType' has no len() เกิดเมื่อใช้ len() บน object ที่ค่าเป็น None

วิธีแก้: 1) อย่า assign ผลลัพธ์ built-in list methods เช่น sort() ให้ตัวแปร 2) ถ้าไม่ได้ ตรวจสอบว่าโปรแกรมมี "return" statements ครบถ้วน

ตอนนี้คุณพร้อมแก้ปัญหานี้อย่าง Python professional แล้ว!