Python Forum

Full Version: Trying to set an instance variable to current value of a class variable
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I thought this code would produce the following:

nic_id 1 has 5 ports
nic_id 2 has 2 ports

but instead it produces:

nic_id 3 has 5 ports
nic_id 3 has 2 ports

Is there a way to assign the current value of the class variable Count to the instance variable nic_id?

Here is the code:
class NIC:
    Count = 0

    def __init__(self, num_ports):
       
       self.nic_id = NIC.Count
       self.num_ports = num_ports
       NIC.Count += 1
       
    def displayNIC(self):
       print ("nic_id %d has %d ports" % (NIC.Count, self.num_ports))
       
nic1 = NIC(5)
nic2 = NIC(2)

print (nic1.displayNIC())
print (nic2.displayNIC())
You did, you're just not displaying the results correctly. On line 11 you are displaying the class attribute NIC.Count, not the instance attribute nic_id.

If you want the first one to be id 1, you need to move line 8 to before line 6.
Shift code NIC.Count += 1 in method displayNIC i.e. line 12
Thanks ichabod801. I see the user error.