Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python
Python
  1. วิธี Pass Keyword Parameters ให้ Function ใน Python

    ใช้ **kwargs (double asterisk) รับ keyword arguments เป็น dictionary ตัวอย่าง def print_kwargs(**kwargs): print(kwargs) print_kwargs(kwargs_1=Whale, kwargs_2=5, kwargs_3=False, kwargs_4=2.1) ผลลัพธ์ {kwargs_4: 2.1, kwargs_1: Whale, kwargs_2: 5, kwargs_3: False} เหมือน *args แต่ต้องระบุ keyword

  2. วิธี Call Function ด้วย Argument List ใน Python

    *args ใน parameter: pack arguments ที่เหลือเป็น list *args ใน function call: unpack list เป็น arguments ตัวอย่าง def baz1(foo, *args): # with star foo(*args) def baz2(foo, args): # without star foo(*args) def foo2(x, y, z): print(x + y + z) baz1(foo2, 2, 3, 4) baz2(foo2, [2, 3, 4])

  3. Assertions ใน Python คืออะไร และทำงานอย่างไร

    Assertion: sanity-test หลัง testing เสร็จ คล้าย raise-if-not ถ้า expression เป็น False → raise AssertionError ทำงานด้วย assert statement ใช้ที่ไหน: ต้นฟังก์ชัน: check valid input หลังฟังก์ชัน: check valid output ตัวอย่าง x, y = 8, 8 assert x < y, x and y are equal ผลลัพธ์ AssertionError: x and y a

  4. วิธี Raise Python Exception จาก C Extension

    ต้องสร้าง C extension module พร้อม setup.py setup.py from distutils.core import setup, Extension setup(name=helloworld, version=1.0, ext_modules=[Extension(helloworld, [hello.c])]) Build: $ python setup.py install Test ใน Python # test.py import helloworld try: print(helloworld.helloworld

  5. วิธี Print Python Exception/Error Hierarchy

    ใช้ inspect.getclasstree() และ __subclasses__() ตัวอย่าง import inspect print(The class hierarchy for built-in exceptions is:) inspect.getclasstree(inspect.getmro(BaseException)) def classtree(cls, indent=0): print(. * indent, cls.__name__) for subcls in cls.__subclasses__(): class

  6. วิธี Catch Python Exception ใน List Comprehension

    List comprehension มีแค่ expressions ไม่มี statements → ไม่สามารถ catch exception ได้โดยตรง Workaround: Delegate ไปยัง helper function ตัวอย่าง foo = (5, 7, 1, 0, 9) def bar(self): try: return [1/i for i in foo] except ZeroDivisionError as e: print(e) bar(foo) ผลลัพธ์ integ

  7. วิธี Handle Python Exception ภายใน Loop

    ห่อ loop ไว้ใน try-except ตัวอย่าง a = [] foo = redbullz try: for i in foo: a.append(i) print(a[8]) # IndexError except Exception as e: print(e) ผลลัพธ์ list index out of range Process finished with exit code 0

  8. ความแตกต่างระหว่าง except Exception as e และ except Exception, e ใน Python

    Functionality เหมือนกัน แตกต่างที่ Python version Python 2.5 และก่อน: ใช้ comma except Exception, e: (as ยังไม่รองรับ) Python 2.6+: ใช้ทั้ง comma และ as ได้ Python 3.x: ต้องใช้ as เท่านั้น ข้อดีของ as: รองรับ multiple exceptions สวยงาม except (Exception1, Exception2) as err # สวยกว่า except (Exce

  9. Exception Handling ใน Python คืออะไร

    Error: ผิดพลาดตอน compile (syntax error) abe = 5 SyntaxError: cant assign to literal Exception: Error ตอน execution (runtime) syntactically correct แต่ run ไม่ได้ abe < 5 NameError: name abe is not defined Python script พบ error ที่ handle ไม่ได้ → raise exception → create exception object ถ้าไม่ ha

  10. อธิบาย Try Except Finally Statements ใน Python

    try-except: จับและจัดการ exceptions ตัวอย่าง try: apple + 6 except Exception: print(Cannot concatenate str and int objects) ผลลัพธ์ Cannot concatenate str and int objects หลีกเลี่ยง traceback ด้วยข้อความง่ายๆ finally: optional clause รันเสมอ ก่อนออกจาก try statement (cleanup actions) ตัวอย่า

  11. Assert Statement ใน Python ใช้ทำอะไร

    Syntax: assert , ถ้า condition เป็น False → raise AssertionError พร้อม message ใช้สำหรับ: Debugging code ตรวจสอบ user-defined constraints (preconditions, postconditions) ไมใช้สำหรับ catch code errors (เช่น x/0) เพราะ Python จัดการเอง ตัวอย่าง y, x has to be smaller than y ผลลัพธ์ AssertionError:

  12. วิธี Handle Exception ใน Python (พื้นฐาน)

    วิธีง่ายที่สุด: try-except block ตัวอย่าง try: fob = open(test.txt, r) fob.write(This is my test file for exception handling!!) except IOError: print(Error: cant find the file or read data) else: print(Write operation is performed successfully on the file) fob.close() ผลลัพธ์ Err

  13. วิธี Catch KeyError Exception ใน Python

    KeyError raised เมื่อ key ไม่อยู่ใน dictionary ตัวอย่าง import sys try: s = {a:5, b:7}[c] except: print(sys.exc_info()) ผลลัพธ์ (, KeyError(c,), )

  14. Best Practices สำหรับ Exception Handling ใน Python

    Best practices สำคัญ: Exceptions ดีกว่า error codes - Python core และ stdlib ใช้ exceptions อย่าใช้ exceptions สำหรับ flow control - ใช้สำหรับ exceptional situations เท่านั้น Handle exceptions ที่ level ที่รู้จักจัดการ - ไม่ควร catch ทุกอย่างที่ low level Programming errors (IndexError, TypeError,

  15. วิธี Catch Multiple Exceptions ในบรรทัดเดียว (Except Block) Python

    ใช้ tuple ใน except clause ใช้ as สำหรับ variable Syntax try: raise_certain_errors() except (CertainError1, CertainError2, ...) as e: handle_error() Python 2.6/2.7: comma ยังทำงานแต่ deprecated Python 3: ต้องใช้ as เท่านั้น Parentheses จำเป็น เพราะ comma ใช้ assign error object ตัวอย่าง try:

Total 9001 -คอมพิวเตอร์  FirstPage PreviousPage NextPage LastPage CurrentPage:6/451  20-คอมพิวเตอร์/Page Goto:1 2 3 4 5 6 7 8 9 10 11 12