Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 创建类和输出_Python_Class - Fatal编程技术网

Python 创建类和输出

Python 创建类和输出,python,class,Python,Class,我试图创建一个person类,输入详细信息并输出特定的person类,但是现在我只有一堆变量,我是从变量输出的,而不是从类输出的 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 = Per

我试图创建一个person类,输入详细信息并输出特定的person类,但是现在我只有一堆变量,我是从变量输出的,而不是从类输出的

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))

正如您在代码中看到的,我只是创建了变量,为变量分配了一些内容,并打印了变量,我不确定如何正确使用类系统,任何帮助都会很好。谢谢您,我想您只需要打印类实例并接收格式化输出。为此,您需要在类中实现此方法:

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)

你的问题到底是什么?我需要输出一个类,而不是从变量输出“输出一个类”是什么意思?我需要向一个类添加“john”,并能够通过简单地打印“john”而不是打印(john.\u firstname)等来输出john…请同时修复
\u init\uuu
方法的缩进!