【问题标题】:Method is considering "self" as an argument variable方法将“self”视为参数变量
【发布时间】:2021-11-13 06:00:06
【问题描述】:

我有两个类,在第二个类中我定义了一个方法,该方法从第一个类中实例化一个对象,为其属性分配一个值,然后打印它。

问题是当我使用以下方法调用函数时:

test.Pprint(5)

我得到了错误。

TypeError: Pprint() missing 1 required positional argument: 'x'

我的代码:

class node():
    def __init__(self, test):
        self.test = test
    
class test():
    def Pprint(self, x):
        rootnode = node(x)
        print(rootnode.test)

当我删除关键字self 时,一切都按预期进行。据我所知self 不应被视为论点。有什么问题?

【问题讨论】:

  • self 是参数。你没有传入xtest 是一个类,而不是一个保险。致电test().Pprint(5)
  • @MadPhysicist insurance -> instance
  • @MattDMo。自动更正很有趣:)

标签: python class methods typeerror self


【解决方案1】:

这是蟒蛇的魔法。当从类对象 test.Pprint(x) 调用时,它是一个需要 2 个参数的函数。当从实例调用时,test().Pprint(x)python 将其转换为方法并自动添加对该实例的引用作为第一个参数。在您的情况下,Pprint 不使用该类的任何功能,因此它可以是静态方法。

class test:
    @staticmethod
    def Pprint(x):
        rootnode = node(x)
        print(rootnode.test)

现在它可以在类或实例中工作

test.Pprint(x)
t = test()
t.Pprint(x)

【讨论】:

  • 那非常有帮助!
猜你喜欢
  • 1970-01-01
  • 2020-05-23
  • 1970-01-01
  • 2012-02-07
  • 2021-01-24
  • 1970-01-01
  • 1970-01-01
  • 2015-09-30
  • 1970-01-01
相关资源
最近更新 更多