首页 > 解决方案 > Python2.7:我如何为每个类对象制作可数 ID

问题描述

我想给我在 Employee 类中创建的每个员工一个 ID ,但自动

这是代码:

class employees :
    def  __init__(self,first,last,pay):
        self.first_name = first
        self.last_name = last
        self.pay = pay
        self.email = first + '.' + last + '@company.com'
        self.full_name = first + ' '+last
        self.facebook_link = 'FB.com/'+ self.full_name

标签: python-2.7oop

解决方案


class employees:
    uid = 0
    def  __init__(self,first,last,pay):
        self.first_name = first
        self.last_name = last
        self.pay = pay
        self.email = first + '.' + last + '@company.com'
        self.full_name = first + ' '+last
        self.facebook_link = 'FB.com/'+ self.full_name

        employees.uid += 1
        self.uid = employees.uid

现在,当我通过实例创建并打印它们时uid

emp1 = employees('Abhishek', 'Babuji', 1000)
print(emp1.uid)

输出:1

emp2 = employees('Abhishek1', 'Babuji1', 10001)
print(emp2.uid)

输出:2

每次你进去__init__ employees.uid时都会增加 1,然后使用它分配给实例self.uid


推荐阅读