Python3问题TypeError:object takes no parameters

时间是一切财富中最宝贵的财富。--------德奥弗拉斯多

Python中关键字变量和特殊函数,都是以__xxx__来表示的,初学Python的朋友,需要注意其中变量名中前后是有两个下划线(_)的,如果不注意,调用内部关键字变量和特殊函数时,将会出现错误:

'A test module'

import sys

def test():

args = sys.argv

if len(args)==1:

print('Hello,World!')

elif len(args)==2:

print('Hello, %s!' % args[1])

else:

print('Too many arguments!')

if _name_=='_main_':

test()

运行报错

"E:\python\python project\myfirst\venv\Scripts\python.exe" "E:/python/python project/myfirst/vari/_first_module.py"

Traceback (most recent call last):

File "E:/python/python project/myfirst/vari/_first_module.py", line 17, in

if _name_=='_main_':

NameError: name '_name_' is not defined

class Student(object):

def __init__(self,name,age):

self.name=name

self.age=age

def print_core(self):

print('%s:%s' % (self.name,self.age))

stu1 = Student('tpc',26)

stu1.print_core()

报错

"E:\python\python project\myfirst\venv\Scripts\python.exe" "E:/python/python project/myfirst/vari/_first_class.py"

Traceback (most recent call last):

File "E:/python/python project/myfirst/vari/_first_class.py", line 10, in

stu1 = Student('tpc',26)

TypeError: object() takes no parameters

两个错误都是由于关键字变量和特殊函数都是使用__XXX__这样前后双下划线的格式,调用时正确调用即可避免问题出现,在此测试如下:

class Student(object):

def _init_(self,name,age):

self.name=name

self.age=age

def print_core(self):

print('%s:%s' % (self.name,self.age))

stu1 = Student('tpc',26)

stu1.print_core()

运行结果:

"E:\python\python project\myfirst\venv\Scripts\python.exe" "E:/python/python project/myfirst/vari/_first_class.py"

tpc:26

  • 发表于:
  • 原文链接http://kuaibao.qq.com/s/20180207G0SMR400?refer=cp_1026
  • 腾讯「云+社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 yunjia_community@tencent.com 删除。

扫码关注云+社区

领取腾讯云代金券