0

Consider the following:

from module1 import foo_ext()

    class A(object):
        x = foo_ext()
        @classMethod
        def foo1():
          . . .
        @classMethod
        def foo2():
          . . .
        @classMethod
        def foo3():
          . . .

Is it true that everytime we call A.foo1() or A.foo2() x class variable is not being assigned again by a call to foo_ext(), only on the first time there is some call to "static class" A with some of its class methods :foo1, foo2, etc?

2 Answers 2

3

Is it true that everytime we call A.foo1() or A.foo2() x class variable is not being assigned again by a call to foo_ext()

Well yes of course why ???

only on the first time there is some call to "static class" A with some of its class methods :foo1, foo2, etc?

Not even. This statement - like all statements at the top-level of class block - are eval'd as part of the class statement execution, which is - assuming the most common case of a class statement at the module's top-level (=> not within a function) - when the module is imported for the first time for a given process.

This:

class Foo(object):
   x = somefunc()

   def bar(self):
       print("foo")

   @staticmethod
   def baaz():
       print("quux")

is actually just syntactic sugar for:

x = somefunc()

def bar(self):
  print("foo")

def baaz():
   print("quux")

attribs = {
    "x" : x,
    "bar": bar,
    "baaz": staticmethod(baaz)
    }

del x
del bar
del baaz

Foo = type("Foo", (object,), attribs)

so why would you expect the x = somefunc() statement to be executed each time you instanciate Foo or call bar or baaz ?

Sign up to request clarification or add additional context in comments.

Comments

1

The issue is that you're creating a class attribute and not an instance attribute.

def in_here():
    print('Called')

    return True

class A:
    x = in_here()

    @classmethod
    def test(cls):
        print('In test')
        return cls.x


A.test()

This will only print Called once. - Because the class attributes are not rebuilt every time you call the class, but rather once when executed.

If you'd like to have it run it more than once, then why not use __init__? or change the class attribute to a property? or better yet, just call the function when required?

Comments

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.