python中的类和函数
我是Python新手,正在尝试类和对象,我有以下脚本:python中的类和函数,python,function,class,python-3.x,Python,Function,Class,Python 3.x,我是Python新手,正在尝试类和对象,我有以下脚本: #!/usr/bin/env python class test: def __init__(self, username): self.username = username def name_again(self): for i in range(0-4): print ("username is %s" %self.username) ahmed = t
#!/usr/bin/env python
class test:
def __init__(self, username):
self.username = username
def name_again(self):
for i in range(0-4):
print ("username is %s" %self.username)
ahmed = test('ahmbor')
ahmed.name_again()
我期待这个脚本打印用户名是ahmbor 5次
当我运行这个脚本时,我什么都没有
请帮助找出这有什么问题您正在告诉范围循环0-4减去0中的4,即-4。因为默认值是从0开始并向上计数,所以这是一个空范围:
>>> range(0-4)
range(0, -4)
>>> len(range(0-4))
0
用逗号代替,用5循环5次,而不是4次。端点不包括:
>>> len(range(0, 4))
4
>>> len(range(0, 5))
5
无论如何,起始点默认为0,所以您不需要。@Eevee:确实如此,但OP显然想要明确定义起始点。