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

วิธีนิยาม Attributes ของคลาสใน Python

Attributes ของคลาส

เกือบทุกอย่างใน Python เป็น Object ทุก Object มี Attributes และ Methods Attributes จึงเป็นพื้นฐานสำคัญ Class เป็น Construct ที่รวบรวม Objects ที่คล้ายกัน Class ก็มี Attributes เช่นกัน มีความแตกต่างระหว่าง Class Attributes และ Instance Attributes: Class Attributes แชร์ระหว่าง Instances แต่ Instance Attributes ไม่แชร์กลับไปยัง Class

ตัวอย่าง: ดู Attributes ด้วย dir()

>>> s = 'abc'
>>> len(dir(s))
71
>>> dir(s)[:5]
['__add__', '__class__', '__contains__', '__delattr__', '__doc__']

>>> i = 123
>>> len(dir(i))
64
>>> dir(i)[:5]
['__abs__', '__add__', '__and__', '__class__', '__cmp__']

>>> t = (1,2,3)
>>> len(dir(t))
32
>>> dir(t)[:5]
['__add__', '__class__', '__contains__', '__delattr__', '__doc__']

ข้อมูลพื้นฐานใน Python ก็มี Attributes เยอะมาก ใช้ dir() ดูได้ จำกัด Output 5 ตัวแรก