I am trying to create a class that uses randomly generated strings as an id for each instance which will later be inherited in another class. Below is a dumbed down version of what I am doing.
class Part():
def __init__(self, type):
import random
import string
self.type = type
# Generate instance ID
self.part_serial = ''.join(random.choice(string.ascii_lowercase + string.digits) for i in range (8))
class Assembly():
def __init__(self, Part):
import random
import string
# Input agruments
Part.__init__(self)
# Use inherited part_serial
self.assembly_serial = Part.part_serial + "-" + ''.join(random.choice(string.ascii_lowercase + string.digits) for i in range (8))
The problem is once I create the part, every time I call the object, the id changes. Is there any way to create an instance variable using a something similar that doesn't change every time the object is called?
test_part = Part("A")
print(test_part.part_serial) # Returns 5347c17a
test_assembly = Assembly(test_part) # Returns fda8721d-47b6c677 but should return 5347c17a-xxxxxx
The error is right in the Assembly
initialization:
def __init__(self, Part):
# Input agruments
Part.__init__(self)
You explicitly reinitialize Part
for some strange reason. This generates a new part number. Why are you doing that? __init__
should be called only once for any object, at its initial creation, and never again. Remove this from Assembly
. Also, keep working through class examples to learn the structure and flow.
N.B. import
statements belong at the top of the file. Your code repeats the import
s every time you create a new object, which is almost always a waste of time.