Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9052875
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T13:17:15+00:00 2026-06-16T13:17:15+00:00

I have a hierarchy of objects in a python module as follows: class BaseObject(object):

  • 0

I have a hierarchy of objects in a python module as follows:

class BaseObject(object):
    initialized = False

    def __init__(self):
        self._initialize()

    @classmethod
    def _initialize(cls):
        print "cls.initialized = "+str(cls.initialized)
        if not cls.initialized:
            cls.x = 1
            cls.initialized = True

class ObjectOne(BaseObject):
    @classmethod
    def double_x(cls):
        cls.x = cls.x * 2
        print cls.x

class ObjectTwo(BaseObject):
    @classmethod
    def triple_x(cls):
        cls.x = cls.x * 3
        print cls.x

if __name__ == '__main__':
    obj_1 = ObjectOne()
    obj_1.double_x()
    obj_2 = ObjectTwo()
    obj_2.triple_x()

When I run this module I would like the output to be:

cls.initialized = False
2
cls.initialized = True
6

But what I get is:

cls.initialized = False
2
cls.initialized = False
3

What do I not understand?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T13:17:17+00:00Added an answer on June 16, 2026 at 1:17 pm

    You need to use the full classname to set class variables. cls in double_x and tripple_x will refer to subclasses (ObjectOne and ObjectTwo, respectively), and setting attributes on those subclasses will store new variables, not alter the class variable BaseObject.x. You can only alter base class variables by directly accessing them.

    Using your code, we get:

    >>> obj_1 = ObjectOne()
    cls.initialized = False
    >>> obj_1.double_x()
    2
    >>> obj_2 = ObjectTwo()
    cls.initialized = False
    >>> obj_2.triple_x()
    3
    >>> BaseObject.x
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: type object 'BaseObject' has no attribute 'x'
    >>> BaseObject.initialized, ObjectOne.initialized, ObjectOne.x, ObjectTwo.initialized, ObjectTwo.x
    (False, True, 2, True, 3)
    

    What happened is that in _initialize(), cls was set to ObjectOne or ObjectTwo, depending on what instance you created, and each subclass got their own copies of the variables initialized and x.

    Using BaseObject._initialize() (to ensure that BaseObject is initialized, and not the subclasses) gives:

    >>> obj_1 = ObjectOne()
    cls.initialized = False
    >>> obj_1.double_x()
    2
    >>> obj_2 = ObjectTwo()
    cls.initialized = True
    >>> obj_2.triple_x()
    3
    >>> BaseObject.x, ObjectOne.x, ObjectTwo.x
    (1, 2, 3)
    >>> BaseObject.initialized
    True
    >>> 'x' in ObjectOne.__dict__
    True
    >>> 'initialized' in ObjectOne.__dict__
    False
    >>> 'initialized' in ObjectTwo.__dict__
    False
    

    So now _initialize() used BaseObject as the target to set initialized and the initial value for x, but double_x and triple_x still used their own subclasses to set the new value of x and are not sharing that value through BaseObject.

    The only option you have to set class variables on a specific base class is to refer to it directly in all class methods:

    class BaseObject(object):
        initialized = False
        def __init__(self):
            BaseObject._initialize()
    
        @classmethod
        def _initialize(cls):
            print "cls.initialized = "+str(cls.initialized)
            if not cls.initialized:
                cls.x = 1
                cls.initialized = True
    class ObjectOne(BaseObject):
        @classmethod
        def double_x(cls):
            BaseObject.x = BaseObject.x * 2
            print cls.x
    
    class ObjectTwo(BaseObject):
        @classmethod
        def triple_x(cls):
            BaseObject.x = BaseObject.x * 3
            print cls.x
    

    which would give:

    >>> obj_1 = ObjectOne()
    cls.initialized = False
    >>> obj_1.double_x()
    2
    >>> obj_2 = ObjectTwo()
    cls.initialized = True
    >>> obj_2.triple_x()
    6
    

    Note that I called BaseObject._initialize() to make sure that cls is BasObject and not a subclass. Then, when setting x the double_x and triple_x methods still refer directly to BaseObject to ensure that the variable is set directly on the base class. When reading the value of x the above example still uses cls, which uses the class MRO to find x on the base class when not set locally.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a hierarchy of objects define as follows: class Request { RequestType type
class A(object): def __init__(self, a, b, c): #super(A, self).__init__() super(self.__class__, self).__init__() class B(A): def
I have the following hierarchy of classes: class ProfileUpdateView( UpdateView, LoggerMixin ): def get_context_data(self,
Suppose we have the following class hierarchy: class ClassA: @property def foo(self): return hello
I have the following two classes : class DbQuery: def __init__(self,query): self.query = query
I have a python class hierarchy, that I want to extend at runtime. Furthermore
I have a python code like this. File named mymodule.py class MyBase(object): pass File
I have the following hierarchy of objects in Entity Framework Code First: class Parent
I have a class hierarchy, each member of which may create IDisposable objects. I
I have a hierarchy of objects, Order, Contact, Address: public class Order { public

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.