我需要在 python 中理解這些東西,這里有一些代碼。我想要一個很好的描述。當我使用第一個代碼時,“self”是必要的,當我使用第二個代碼時,“self”給了我一個錯誤。如何?
class Sample():
def example(self, x, y):
z = x y
return print(z)
x = Sample()
x.example(1,2)
class Sample():
def example(x, y):
z = x y
return print(z)
Sample.example(1,2)
這段代碼給了我一個錯誤,我不知道我錯在哪里
class Sample():
def __init__(self, x, y):
self.x = x
self.y =y
def example(self):
z = self.x self.y
return print(z)
x = Sample()
x.example(1,2)
錯誤
Traceback (most recent call last):
File "c:\Users\Lenovo\Documents\PP\Advance python\example.py", line 13, in <module>
x = Sample()
TypeError: __init__() missing 2 required positional arguments: 'x' and 'y'
另一個有錯誤的代碼
def example(self):
z = self.x self.y
return print(z)
example(1,2)
錯誤
Traceback (most recent call last):
File "c:\Users\Lenovo\Documents\PP\Advance python\example.py", line 8, in <module>
example(1,2)
TypeError: example() takes 1 positional argument but 2 were given
我非常感謝您的幫助。
uj5u.com熱心網友回復:
該__init__方法是一個建構式,因此它本質上是初始化物件的屬性。因此,您應該在創建物件時傳遞引數。當你使用self這意味著那些屬性/方法與同一個類有關。
class Sample:
def __init__(self, x, y):
self.x = x
self.y = y
def example(self):
z = self.x self.y
return print(z)
x_object = Sample(1, 2)
x_object.example()
因此,與其將引數傳遞給x.example您,不如將它們傳遞給Sample()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/421386.html
標籤:
上一篇:如何在函式的某個斷點處退出代碼
