python - 在 Python 中打印具有多个值的类

标签 python class

我在这个网站上搜索了很长时间,所以我希望以前没有人问过这个问题 - 如果有人问过,我深表歉意。我是第一次学习类(class),并且正在与多个用户一起上课(可能超过 50 个,但目前,我的示例中只有 2 个)。我想做的是获得有关用户/员工的某些信息,并能够一次打印所有这些信息……以一种不完全碍眼的方式!这是我尝试过的:

class User:

    def __init__(self, user_id, first, last, address):
        self.user_id = user_id
        self.first = first
        self.last = last
        self.address = address
        self.email = first + '.' + last + '@python.com'

    def all_users(self):
        print()
        print('User ID: {} First Name: {} {} {} {}'.format(self.user_id, self.first, self.last, self.address, self.email))
        print()


user_1 = User(123, 'Kim', 'N', 'London')

user_2 = User(312, 'Chris', 'E', 'Japan')

print(all_users(User))

这是我收到的错误消息:

print('User ID: {} First Name: {} {} {} {}'.format(self.user_id, self.first, self.last, self.address, self.email))
AttributeError: type object 'User' has no attribute 'user_id'

在此先感谢您的帮助或指导。

最佳答案

听起来您希望 User 类包含所有用户的列表。

这称为类变量,因为它附加到类本身,而不是附加到类的特定实例

示例代码:

class User(object):

    users = []

    def __init__(self, first, last):
        self.first = first
        self.last = last

        # now that this instance is fully initialized, add it
        # to the master list of users
        User.users.append(self)

    def __str__(self):
        return '{} {}'.format(self.first, self.last)

    @staticmethod
    def all_users():
        for user in User.users:
            print (user)

user_1 = User('Kim', 'Smith')
user_2 = User('Chris', 'Jones')

User.all_users()

关于python - 在 Python 中打印具有多个值的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49698548/

相关文章:

c++ - 如何链接多个运算符[]

java - 使用类作为变量标识符?

Python从任意类继承方法

python - 'ManyToManyDescriptor' 类型的参数不可迭代

python - 使用许多没有成员函数的子案例编写干净的 Julia 代码

Python,关于分组函数的建议

c++ - rand() 函数 C++

java - isInstance 中的 ClassNotFoundException

python - 如何计算列表列表中存在的重复项目?

python - 快速解析类似 csv 的文件