无法在python中打印所需的输出

时间:2014-06-12 06:02:11

标签: python

class Person:
    def __init__(self,name,age): #contructor method
        self.name = name
        self.age = age 
        print '(0) has been born'.format(self.name) 
p1 = Person("sam", 23)
p2 = Person("sunny", 22)

Im getting output:-
(0) has been born
(0) has been born
Expected output:-
sam has been born
sunny has been born

我在这里尝试了解以 init 方法开头的特殊方法。但我没有得到所需的输出。有帮助吗?感谢

3 个答案:

答案 0 :(得分:6)

您必须使用花括号 {}

print '{0} has been born'.format(self.name)

注意:您可以从Python文档中看到this link以获取更多示例。

答案 1 :(得分:0)

这对我有用;

class Person:
    def __init__(self,name,age): #contructor method
        self.name = name
        self.age = age 
        print self.name+' has been born'
p1 = Person("sam", 23)
p2 = Person("sunny", 22)

答案 2 :(得分:0)

使用{}点击LIVE IDEONE

的Python

class Person:
    def __init__(self,name,age): #contructor method
        self.name = name
        self.age = age 
        print '{0} has been born'.format(self.name) 
p1 = Person("sam", 23)
p2 = Person("sunny", 22)

标准输出

sam has been born
sunny has been born