# Python ## 實作前導課程:class & object Part II ### 2022 / 4 / 28 ### Tony --- ## Class Attributes ## @classmethod ## @staticmethod ---- ### Class Attributes 前面都只有創建綁定在物件上的屬性 但其實class可以創建綁定class的屬性 這樣整個class都共用一個屬性 不會因為不同的物件而改變 ---- Example ```python= class Person: number_of_people = 0 # An attribute for the whole class # not specific to the objects def __init__(self, name): self.name = name Person.number_of_people += 1 p1 = Person("Tim") p2 = Person("Joe") print(Person.number_of_people) #2 print(p1.number_of_people) #2 ``` ---- ### @classmethod 有時你會需要class的函式操作的東西是class attributes 且不想要透過創造物件來執行 這種時候就可以使用 @classmethod ---- 使用方式:寫在你不想用物件呼叫的函式上方 這時引數self會變成cls,class的意思 ```python= class student: school = "HSNU" @classmethod def get_school(cls): return cls.school ``` ---- Example ```python= # @classmethod class Person: number_of_people = 0 GRAVITY = -9.8 # Attributes for the whole class, not specific to the objects def __init__(self, name, age): self.name = name self.age = age # Person.number_of_people += 1 Person.add_person() @classmethod # wrote on the function so that it can be called without creating an object def get_number_of_people(cls): return cls.number_of_people # The things returned cannot be the attributes of the objects # Otherwise there will be a mistake @classmethod def add_person(cls): cls.number_of_people += 1 '''# Like this. It's incorrect @classmethod def get_name(self): return self.name ''' p1 = Person("Tim", 30) p2 = Person("Joe", 15) print(Person.get_number_of_people()) #2 ``` ---- ### @staticmethod 有時候,class只是用來整理function 例如你把一堆數學相關的function 丟進一個Math的class 這種時候你根本不想要呼叫物件來執行function <font color = 'FFF300'>只想單純呼叫</font> 這種時候就可以用@staticmethod ---- 使用方式:寫在該函式上方 ```python= # @staticmethod class Math: @staticmethod def add_five(x): # It's just a function defined in the "Math" class return x+5 @staticmethod def pr(): print("run") print(Math.add_five(5)) ```
{"metaMigratedAt":"2023-06-16T23:58:05.535Z","metaMigratedFrom":"YAML","title":"Python實作前導課程:class & object Part II","breaks":true,"slideOptions":"{\"transition\":\"slide\",\"theme\":null}","contributors":"[{\"id\":\"4f731eff-9d88-41f4-af56-2e3e02f20cfc\",\"add\":2264,\"del\":0}]"}
    123 views