Search code examples
pythonpython-2.7class-attributes

How to set class attributes in python


I have class attributes in my class, that I want to set dynamically, here's a code example

class Something:
     attribute1 = 42                 # this is shared between all class instances
     def _init_(self, value):
          self.value = value

my question is: Is there a way to set that class attribute (attribute1) to some value, the same way that I can set my object instance attributes like this:

something = Something(value)

Solution

  • Yes just do

    Something.attribute1 = "some value"    
    

    Class attributes can be accessed via the class name. You can do this inside any function defined in the class or even outside of it.