เมื่อเราประกาศตัวแปรภายในคลาสแต่อยู่นอกเมธอดใดๆ จะถูกเรียกเป็นคลาสหรือตัวแปรสแตติกใน python.Class หรือตัวแปรสแตติกสามารถอ้างอิงผ่านคลาสได้ แต่ไม่สามารถอ้างอิงผ่านอินสแตนซ์ได้โดยตรง
ตัวแปรคลาสหรือสแตติกค่อนข้างแตกต่างและไม่ขัดแย้งกับตัวแปรสมาชิกอื่นที่มีชื่อเดียวกัน ด้านล่างเป็นโปรแกรมสาธิตการใช้คลาสหรือตัวแปรสแตติก -
ตัวอย่าง
class Fruits(object):
count = 0
def __init__(self, name, count):
self.name = name
self.count = count
Fruits.count = Fruits.count + count
def main():
apples = Fruits("apples", 3);
pears = Fruits("pears", 4);
print (apples.count)
print (pears.count)
print (Fruits.count)
print (apples.__class__.count) # This is Fruit.count
print (type(pears).count) # So is this
if __name__ == '__main__':
main() ผลลัพธ์
3 4 7 7 7
อีกตัวอย่างหนึ่งที่แสดงให้เห็นถึงการใช้ตัวแปรที่กำหนดไว้ในระดับชั้นเรียน -
ตัวอย่าง
class example: staticVariable = 9 # Access through class print (example.staticVariable) # Gives 9 #Access through an instance instance = example() print(instance.staticVariable) #Again gives 9 #Change within an instance instance.staticVariable = 12 print(instance.staticVariable) # Gives 12 print(example.staticVariable) #Gives 9
ผลลัพธ์
9 9 12 9