0

i have a case where i create a class inside an outer function and then return that class. the class has a specified parent class. i would like that class variable to be accessible by class methods on the parent class, these methods are called at class initialization time. in summary, i need to be able to set a class variable (not hardcoded) so that it is available before initializing other, hardcoded class variables.

here's some sample code to make that clearer:

class Parent(object):
    class_var = None

    @classmethod
    def get_class_var_times_two(cls):
        return cls.class_var * 2


def outer_function(class_var_value):

    class Child(Parent):
        other_var = Parent.get_class_var_times_two() # <-- at this point, somehow Child's class_var is set to class_var_value

Not sure if this is even possible in python. Maybe class_var_value doesn't need to be passed through the outer function. I tried using metaclasses and forcing the variable through in the class attribute dictinoary, but couldn't figure out how to set class_var on Child early enough so that it was set prior to initializing other_var. If that was possible, then this would all work. Any thoughts are appreciated!

Edit: also considered making other_var a lazy property, but that isn't an option for my use case.

2
  • is this a class that gets instansiated at some point or is it just a bunch of class level vars and funcs? Commented Sep 8, 2012 at 2:32
  • is this an actual case? is it always just *2 ? could you just do other_var=class_var_value*2? Commented Sep 8, 2012 at 2:37

1 Answer 1

1

Calling Parent.get_class_var_times_two() calls the function with cls = Parent, and so consequently the value of Parent.class_var will be used (regardless of what context you call the function from).

So, what you want to do is call Child.get_class_var_times_two(). Trouble is, Child doesn't get defined until the class block finishes. You therefore need to do something like this (assuming you don't use a metaclass):

def outer_function(class_var_value):
    class Child(Parent):
        class_var = class_var_value
    Child.other_var = Child.get_class_var_times_two()
Sign up to request clarification or add additional context in comments.

3 Comments

can you just set a variable like that? wouldnt you need to declare other_var to none or something in the child class?
By default, any pure-Python object (including class objects) can have attributes added at any time; this is part of the dynamic nature of Python. Note that some objects, such as primitive types, extension types or objects with __slots__ may restrict this ability.
man I swear Ive gotten errors doing that before ...but your right it works fine (I guess I coulda just tested myself earlier ... but I was bein lazy

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.