Search code examples
pythonpython-3.xclassooppython-object

Python; working with instance variable created by a method


Im a bit of a beginner when it comes to classes.

I have a class defined as follows (simplified for purposes of this post)

class worksheet:
    def __init__(self, filename):
        self.filename = (filename).strip().replace(" ","")
    def idMaker(self):
        number = '{:05d}'.format(random.randrange(1,99999))
        sheetId = self.filename+str(number)

I want to be able to get the 'sheetID' for each instance by saying something like the following (again, this might be completely incorrect):

newSheet = worksheet('testsheet')
id = newSheet.sheetID

This of course does not work, but I am not sure what I need to do to make it work.

I want to make sure the ID stays constant and doesnt recreate itself with new random numbers.

Thank you in advance


Solution

  • Just generate and assign the id in __init__. In general, as a user of the class, you don't want to care about generating the id yourself. As far as you're concerned, instantiating Worksheet gives you a complete, usable object.

    import random
    
    class Worksheet(object):
        def __init__(self, filename):
            self.filename = filename.strip().replace(' ','')
    
            number = '{:05d}'.format(random.randrange(1,99999))
            self.sheet_id = self.filename + str(number)
    
    sheet = Worksheet(' some filename with spaces ')
    print(sheet.filename)
    print(sheet.sheet_id)
    

    will output

    somefilenamewithspaces
    somefilenamewithspaces68237