1

Given the class

class A(object): 
    def __init__(self): 
        self.x = 'hello'

one can recreate is dynamically with type.

type('A', (object,), {'x': 'hello'})

Is it possible to create class level variables with type?

class A(object): 
    my_class_variable = 'hello'

1 Answer 1

2
In [154]: A = type('A', (object,), {'my_class_variable':'hello'})

In [155]: A.my_class_variable
Out[157]: 'hello'

In your first example, type('A', (object,), {'x': 'hello'}), A.x is a class attribute, not an instance attribute too.

To make a class with the __init__ you posted, you would first need to define the __init__ function, then make that __init__ a class attribute:

In [159]: def __init__(self):
   .....:       self.x = 'hello'
   .....: 

In [160]: A2= type('A', (object,), {'__init__':__init__})

In [161]: 'x' in dir(A2)   
Out[161]: False            # x is not a class attribute

In [162]: 'x' in dir(A2()) 
Out[162]: True             # x is an instance attribute
Sign up to request clarification or add additional context in comments.

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.