Reputation: 346
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
Upvotes: 0
Views: 56
Reputation: 508
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
Upvotes: 2
Reputation: 2477
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)
Upvotes: 0