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

วิธีประกาศ Attribute ใน Python โดยไม่มีค่า

ใน Python (และภาษาอื่นๆ) มีค่าที่หมายถึง "ไม่มีค่า" คือ None

class Student:
    StudentName = None
    RollNumber = None

เหล่านี้คล้าย Instance Variables ไม่ใช่ Class Variables ดังนั้นเขียนใน __init__ ดีกว่า:

class Student(object):
    def __init__(self):
        self.StudentName = None
        self.RollNumber = None

Python กำหนด None โดยอัตโนมัติหากฟังก์ชันไม่ Return ค่า:

def h():
    pass
k = h()  # k มีค่า None