使用print()无法获得所需的输出

时间:2018-01-12 16:46:24

标签: python

我的python代码如下:

class Student():

        def __init__(self, name, branch, year):
            self.name = name
            self.branch = branch
            self.year = year
            # Variables name,branch and year are instance variables
            # Different objects like Student1, Student2 will have diff values of these variables.
            print('Student object is created for Student : ', name)

       def print_details(self):
            print('Name:', self.name)
            print('Branch:', self.branch)
            print('Year:', self.year)

Stud1 = Student('AAkash','ECE',2015)
Stud2 = Student('Vijay','IT',2017)

Stud1.print_details()
Stud2.print_details()

我的输出是:

('Student object is created for Student : ', 'AAkash')
('Student object is created for Student : ', 'Vijay')
('Name:', 'AAkash')
('Branch:', 'ECE')
('Year:', 2015)
('Name:', 'Vijay')
('Branch:', 'IT')
('Year:', 2017)

而在我要求的输出中,我想要声明如下:

Name : AAkash
Branch : CSE

1 个答案:

答案 0 :(得分:1)

您使用的是python-3.x打印语法,但您可能只是运行python 2.7。 python2中的print不是一个函数,它只是一个函数。它只是一个函数。

当你做

print('Name:', self.name)

你告诉print语句打印一个包含2个项目的元组 - 这正是它的作用

你可以删除括号并让它看起来像这样:

print 'Name:', self.name
print 'Branch:', self.branch
print 'Year:', self.year

会打印你想要的东西(实际打印多个项而不是元组本身)

你可以从你的代码中获取python3样式的print函数(从python 2.7开始):

from __future__ import print_function

它会为您提供所需的输出

相关问题