Static Method

Static Method គឺ​ជា method ទាំងឡាយ​ណា​ដែល​មិន​ត្រូវការ instance ជា argument សំរាប់​ parameter self ហើយ​ក៏​គ្មាន parameter self នៅ​ក្នុង​នោះ​ដែរ​។ ដើម្បី​បង្កើត static method យើង​ត្រូវ​ធ្វើ​ដូច​ខាង​ក្រោម​នេះ៖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Cash():
    def __init__(self):
        print('The constructor has been called.')
 
    def display():
        print('Show info.')
 
    display = staticmethod(display)
 
 
money = Cash()
 
Cash.display()
money.display()
1
2
3
The constructor has been called.
Show info.
Show info.

ជារួម static method មាន​សណ្ឋាន​ដូច​ជា function ធម្មតា​នៅ​ខាង​ក្រៅ​ថ្នាក់​ដែរ ទោះ​ជា​វា​ត្រូវ​បាន​បង្តើត​ឡើង​នៅ​ក្នុង​ថ្នាក់​យ៉ាងណា​ក៏​ដោយ​។ ម៉្យាងទៀត ដោយសារ​តែ static method ត្រូវ​បាន​បង្កើត​ឡើង​នៅ​ក្នុង​ថ្នាក់ ដូចនេះ​គ្រប់​ការយក static method មក​ប្រើ ត្រូវ​តែ​ធ្វើ​ឡើង​តាម​រយៈ​ថ្នាក់​របស់​វា​ឬ instance នៃ​ថ្នាក់​របស់​វា​៕