繁体   English   中英

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

[英]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__方法是一个构造函数,因此它实质上初始化了 object 的属性。 因此,当您创建 object 时,您应该传递 arguments。 当您使用self时,这意味着这些属性/方法与相同的 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()

因此,与其将 arguments 传递给x.example ,不如将它们传递给Sample()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM