LoginSignup
1
2

More than 3 years have passed since last update.

クラスメソッド スタティックメソッド

Posted at
class Person(object):
    kind = 'human'

    def __init__(self):
        self.x = 100

    @classmethod
    def what_is_your_kind(cls):
        return cls.kind

    @staticmethod
    def about(year):
        print('human about {}'.format(year))

print(Person.what_is_your_kind())
Person.about(1999)
実行結果
human
human about 1999

Person.what_is_your_kind()
Person()となっておらずオブジェクトができていないので、
本来はエラーとなる。

しかし、
what_is_your_kindをクラスメソッドにする事で、
what_is_your_kindオブジェクトのメソッドではなく、
クラスのメソッドとなりアクセスできる様になる。

1
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2