处理TypeError: testFunc() missing 1 required positional argument: 'self' -- 没有实例化对象的错误

在Python中,使用类分两步:

  1. 应该先对类进行实例化;

  2. 然后在应用类。注意,实例化的过程是应该待括号的。

# -*-coding: utf-8 -*-

'''在Python中,应该先对类进行实例化,然后在应用类。注意,实例化的过程是应该待括号的。
'''
class TestClass:
    def __init__(self):
        print('In init')
    def testFunc(self):
        print('In testFunc')

'''
ERROR1:
#错误方式:未实例化
print(TestClass.testFunc())
TypeError: testFunc() missing 1 required positional argument: 'self'


ERROR2:
#错误方式,TestClass:未带括号
testInstance = TestClass
print(testInstance.testFunc())
TypeError: testFunc() missing 1 required positional argument: 'self'
'''

#正确方式,TestClass():带着括号
testInstance = TestClass()
print(testInstance.testFunc())

in init
In test testFunc
None

  

原文地址:https://www.cnblogs.com/Barrybl/p/12161922.html