-1

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
  • Please supply the expected [minimal, reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) (MRE). We should be able to copy and paste a contiguous block of your code, execute that file, and reproduce your problem along with tracing output for the problem points. This lets us test our suggestions against your test data and desired output. Also, I don't know what you mean by "call the part" -- you call a function or method; an object is not callable. – Prune May 19 '21 at 22:31
  • Apologies. I am still new to programming and don't know how to use the terminology yet. I updated the code snippet to working example. This is a rough example of the issue I'm running into. I've found for some of the attributes, I can use UUID and it will not change each time the object is referenced (hope that is the correct term) but not all. Some will need to use a for loop with ''.join() like in the code snippet. – Dylan Rowan May 19 '21 at 23:02
  • EDIT: UUID does not work like I thought it would. – Dylan Rowan May 19 '21 at 23:16

1 Answers1

1

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 imports every time you create a new object, which is almost always a waste of time.

Prune
  • 76,765
  • 14
  • 60
  • 81