创建类和输出

时间:2017-12-08 13:50:40

标签: python class

我正在尝试创建一个人类,输入详细信息并输出特定的人类,但此刻我只有一堆变量而且我从变量输出,而不是类

class Person:

def __init__(self, _firstname, _surname, d, m, y):
    self._firstname = _firstname
    self._surname = _surname
    self.d = d
    self.m = m
    self.y = y


john = Person('John','Lennon','8','10','1940')
paul = Person('Paul','McCartney','7','7','1940')


john._firstname = 'John'
john._surname = 'Lennon'
john.d = '8th'
john.m = 'October'
john.y = '1940'


paul._firstname = 'Paul'
paul._surname = 'McCartney'
paul._day = '18'
paul._month = '6'
paul._year = '1943'

print('{} {} \n{} {} {}'.format(john._firstname, 
john._surname, john.d, john.m, john.y))

正如你在代码中看到的那样,我只是简单地创建了变量,为变量分配了一些内容,并打印了变量,我不确定如何正确使用类系统,任何帮助都会非常好,谢谢

1 个答案:

答案 0 :(得分:1)

我认为您只想打印类实例并接收格式化输出。为此,您需要在类中实现此方法:

def __repr__(self):
    return '{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d, john.m, john.y)

然后你可以打印类实例:

print(john)

所以这将是完整的代码:

class Person:
    def __init__(self, _firstname, _surname, d, m, y):
        self._firstname = _firstname
        self._surname = _surname
        self.d = d
        self.m = m
        self.y = y

    def __repr__(self):
        return '{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d, john.m, john.y)


john = Person('John','Lennon','8','10','1940')
paul = Person('Paul','McCartney','7','7','1940')


john._firstname = 'John'
john._surname = 'Lennon'
john.d = '8th'
john.m = 'October'
john.y = '1940'


paul._firstname = 'Paul'
paul._surname = 'McCartney'
paul._day = '18'
paul._month = '6'
paul._year = '1943'

print('{} {} \n{} {} {}'.format(john._firstname, john._surname, john.d,      john.m, john.y))
print(john)