4 回答

TA貢獻1797條經驗 獲得超6個贊
您發布的代碼中有縮進錯誤,您應該首先縮進方法及其內容,這意味著方法在類中。另一方面,self引用實例,它調用特定的方法并提供對所有實例數據的訪問。例如
student1 = Student('name1', 20)
student2 = Student('name2', 21)
student1.some_method(arg1)
在最后一次調用中,在后臺student1傳遞了方法的 self 參數,這意味著所有 student1 的數據都可以通過self參數獲得。
您正在嘗試使用,它沒有實例的數據,旨在在沒有顯式實例的情況下對類相關函數進行邏輯分組,這在方法定義staticmethod中不需要:self
class Student:
...
@staticmethod
def get_biggest_number(*ages):
# do the task here
另一方面,如果您想跟蹤所有學生實例并應用 get_biggest_number 方法自動處理它們,您只需定義類變量(而不是實例變量)并在每個實例上將__init__新實例附加到該列表:
class Student:
instances = list() # class variable
def __init__(self, name, age):
# do the task
Student.instances.append(self) # in this case self is the newly created instance
在get_biggest_number方法中,您只需遍歷Student.instances包含 Student 實例的列表,您就可以訪問instance.age實例變量:
@staticmethod
def get_biggest_number():
for student_instance in Student.instances:
student_instance.age # will give you age of the instance
希望這可以幫助。

TA貢獻1776條經驗 獲得超12個贊
您不應該將 classmethod 與實例方法混淆。在python中,您可以將類中的方法聲明為classmethod。此方法將類的引用作為第一個參數。
class Student(object):
def __init__(self,name,age):
self.name = name
self.age = age
def get_biggest_number(self, *age):
result=0
for item in age:
if item > result:
result= item
return result
@classmethod
def get_classname(cls):
# Has only access to class bound items
# gets the class as argument to access the class
return cls.__name__
@staticmethod
def print_foo():
# has not a reference to class or instance
print('foo')

TA貢獻2041條經驗 獲得超4個贊
self
在 python 中是指創建的類的實例。類似于this
C# 和 Java 中的東西。但是有一些區別,但簡而言之:當您不用self
作方法的輸入時,實際上您是在說此方法不需要任何實例,這意味著此方法是一個static method
并且永遠不會使用任何類屬性。
在您的示例中,我們get_biggest_number
甚至可以調用沒有一個實例的方法,例如,您可以像這樣調用此方法:
Student.get_biggest_number(20,30,43,32)
輸出將是43
.

TA貢獻1909條經驗 獲得超7個贊
self 關鍵字用于表示給定類的實例(對象)。...但是,由于類只是一個藍圖,因此 self 允許訪問 python 中每個對象的屬性和方法。
class ClassA:
def methodA(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
假設 ObjectA 是該類的一個實例。
現在,當調用 ObjectA.methodA(arg1, arg2) 時,python 在內部將其轉換為:
ClassA.methodA(ObjectA, arg1, arg2)
self 變量引用對象本身,代碼變為:
class ClassA:
def methodA(ObjectA, arg1, arg2):
ObjectA.arg1 = arg1
ObjectA.arg2 = arg2
添加回答
舉報