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

วิธีการนับฟังก์ชันของคลาสใน Python

โค้ดตัวอย่างต่อไปนี้แสดงวิธีการแสดงรายการฟังก์ชัน (เมธอด) ของคลาสที่กำหนดโดยใช้โมดูล inspect

ตัวอย่าง

class foo:
    def __init__(self):
        self.x = x
    def bar(self):
        pass
    def baz(self):
        pass

print(type(foo))
import inspect
print(inspect.getmembers(foo, predicate=inspect.ismethod))

ผลลัพธ์

ผลลัพธ์ที่ได้คือ

<type 'classobj'> [('__init__', <unbound method foo.__init__>), ('bar', <unbound method foo.bar>), ('baz', <unbound method foo.baz>)]