Python scopes: setting a class attribute

Status
You're currently viewing only agifford's posts. Click here to go back to viewing the entire thread.
Not open for further replies.

agifford

Ars Tribunus Militum
2,142
If you are referring to:

Code:
class textfile: 
... 
  def totfiles(): 
    print "the total number of text files is", textfile.ntfiles 
  totfiles = staticmethod(totfiles) 
... 
# here we are in "main" 
... 
textfile.totfiles()

Then no, nothing funny is going on, and its not doing what you are trying to do.

textfile.ntfiles & totfiles are not being used until after the class is defined. You are trying to use them during class definition time, big difference.

You could make your variable(bacon) a static method, so that the first time its accessed it calculates the value, instead of at class def time.

Code:
class Foo(object):
    spam = 1
    eggs = 2

    make_bacon = lambda x,y,f : f(x,y)
    slaughter_the_pig = lambda x,y : x+y

    bacon = make_bacon(spam, eggs, slaughter_the_pig)

works too, since you don't ever reference the not yet created Foo, or staticmethods for the class
 
Status
You're currently viewing only agifford's posts. Click here to go back to viewing the entire thread.
Not open for further replies.