Python2.7:如何为每个类对象创建可数的ID

时间:2018-06-27 21:16:56

标签: python-2.7 oop

我想为我在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

1 个答案:

答案 0 :(得分:1)

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将其分配给实例