我需要通过我的代码进行解释,我们需要在哪里定义 init 方法并声明 "self"。如何在每种情况下调用函数在我的代码中给出

I need an explanation through my code, where do we need to define init method and declare "self". How to call a function in each cases give in my code

我需要在 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

非常感谢您的帮助。

__init__ 方法是一个constructor,所以它本质上是初始化对象的属性。所以你应该在创建对象时传递参数。当您使用 self 时,这意味着那些 attribute/methods 与相同的 class.

相关
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()