Python Forum
Trying to set an instance variable to current value of a class variable
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Trying to set an instance variable to current value of a class variable
#1
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())
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Shift code NIC.Count += 1 in method displayNIC i.e. line 12
Reply
#4
Thanks ichabod801. I see the user error.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with writing monitored data to mysql upon change of one particular variable donottrackmymetadata 3 185 Yesterday, 09:55 PM
Last Post: deanhystad
  Commas issue in variable ddahlman 6 388 Apr-05-2024, 03:45 PM
Last Post: deanhystad
  Variable Explorer in spyder driesdep 1 200 Apr-02-2024, 06:50 AM
Last Post: paul18fr
  Mediapipe. Not picking up second variable stevolution2024 1 173 Mar-31-2024, 05:56 PM
Last Post: stevolution2024
Question Variable not defined even though it is CoderMerv 3 251 Mar-28-2024, 02:13 PM
Last Post: Larz60+
  optimum chess endgame with D=3 pieces doesn't give an exact moves_to_mate variable max22 1 251 Mar-21-2024, 09:31 PM
Last Post: max22
  unbounded variable akbarza 3 492 Feb-07-2024, 03:51 PM
Last Post: deanhystad
  Variable for the value element in the index function?? Learner1 8 633 Jan-20-2024, 09:20 PM
Last Post: Learner1
  Variable definitions inside loop / could be better? gugarciap 2 430 Jan-09-2024, 11:11 PM
Last Post: deanhystad
  working directory if using windows path-variable chitarup 2 726 Nov-28-2023, 11:36 PM
Last Post: chitarup

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020