Classについて
·100 文字·1 分
目次
staticmethodとclassmethodの違い #
# instantce method - self is passed
def get_years_from_release(self):
return datetime.datetime.now().year - int(self.release_year)
movie = Movie("Rambo", "1982")
print(f"The movie {movie.name} is {movie.get_years_from_release()} years old.")
# staticmethod - self is not passed
@staticmethod # 'self' is not passed to this method
def get_years_from_release(release_year):
return datetime.datetime.now().year - int(release_year)
movie = Movie("Rambo", "1982")
print(f"The movie {movie.name} is {movie.get_years_from_release(movie.release_year)} years old.")
Class Methods receive a class as first argument. Instance methods receive a class instance as first argument.
Instance methods: receive an instance as first argument(self) Class methods: receive a class as first argument (cls) Static methods: do not receive any special arguments.