0

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

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

The sheetId variable lives within that class's idMaker method, so you cannot access it with a dot operator. If you are trying to create custom IDs for instances of your class, I would recommend doing that in the class constructor __init__ method so it gets assigned on object creation. Maybe consider the following:

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

2 Comments

Not quite right. A new random number is generated with each call, and that does not make for an id
@MosesKoledoye Yea, I'll strike that from my initial answer. I didn't catch that on my first time through the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.