staticmethod
在使用時,不需要用到self自己實例本身時,就可以用staticmethod。
class Car:
def __inti__(self, exterior):
self.exterior = exterior
def move(self):
self.start_engine()
print('move is method called.)
@staticmethod
def start_engine()
print('static method')
Car.start_engine() # 'static method'
classmethod
要是不想創照實例,但是又想在class中可以用其他function,就可以使用classmethod,用cls( )創造一個實例。
class Car:
def __inti__(self, exterior, gasoline):
self.exterior = exterior
self.gasoline = gasoline
def move(self):
self.start_engine()
print('move is method called.)
@classmethod
def start_engine(cls)
print(cls('white', '95').classmethod)
print('static method')
Car.start_engine()
# 95
# static method