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

Declarations ใน Python Class เทียบเท่ากับใน __init__ Method หรือไม่?

Declarations ใดๆ ใน Class (นอกจากใน __init__) และ Declarations ใน __init__ Method ไม่เหมือนกัน โค้ดต่อไปนี้แสดงให้เห็นว่าจริง

ตัวอย่าง

import sys

class foo():
    print 'within class'

    def __init__(self):
        print 'within init'

    def do_smthng(self):
        print 'do something'

def main():
    f = foo()
    f.do_smthng()
    return 0

if __name__ == '__main__':
    sys.exit(main())

Output

within class
within init
do something