【问题标题】:Python3: Can use other than 'self' as a 1st parameter of methods? [duplicate]Python3:可以使用“self”以外的方法作为方法的第一个参数吗? [复制]
【发布时间】:2020-09-20 14:01:57
【问题描述】:

这个代码可以吗

class Point:
    def __init__(self,x,y):
        self.x=x
        self.y=y
    def __str__(self):
        return "Point({},{})".format(self.x,self.y)
p=Point(3,5)
print(p)

修改成如下代码?

class Point:
    def __init__(p,x,y):
        p.x=x
        p.y=y
    def __str__(p):
        return "Point({},{})".format(p.x, p.y)
p=Point(3,5)
print(p)

在这种情况下似乎有效。但这是如此幼稚的情况。我想知道在某些情况下使用“self”以外的东西会导致一些问题。

【问题讨论】:

标签: python python-3.x oop methods naming-conventions


【解决方案1】:

第一个参数是对绑定变量或对象的引用。它使用 self 的约定,但其他任何东西也可以使用。检查文档here

【讨论】:

    猜你喜欢
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-09
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    • 2022-12-15
    相关资源
    最近更新 更多