[解决方法] TypeError: unbound method function must be called with class instance as first argument

关于错误TypeError: unbound method view_user() must be called with New_Login instance as first argument (got nothing instead):

class C:
… def f(self):
… print “hi”

*>>> C.f()
Traceback (most recent call last):
File “”, line 1, in
TypeError: unbound method f() must be called with C instance as
first argument (got nothing instead)
It fails because of TypeError because you didn’t instantiate the class first, you have two choices: 1: either make the method static so you can run it in a static way, or 2: instantiate your class so you have an instance to grab onto, to run the method.

如果你只是想运行静态的function。如下文:

class C:
… @staticmethod
… def f():
… print “hi”

C.f()
hi

或者你想以被实例化的方法运行, 另一个文件需要import,同一个文件也需要把类实例化:如下

class C:
… def f(self):
… print “hi”

c1 = C()
c1.f()
hi

C().f()
hi

如果不知道什么情况用, 问自己几个问题。

  1. 静态方法和普通方法的表现有何不同。
  2. 实例化一个类是什么意思
  3. 静态方法和普通方法运行方式有何不同
  4. 类和对象的区别是什么
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值