0

I was wondering if there was some way to pass a variable to a class, and set a class variable to that passed argument. It would go something like this, but obviously it wouldn't work because it would be inheriting from variable:

def myClass(my_param):
    class_variable = my_param

    @classmethod
    def printVariable(cls):
        print(cls.class_variable)

Thanks.

  • 2
    Is that supposed to say `class myClass`? And is `my_param` meant to be passed to `__init__`? – Carcigenicate Jun 03 '20 at 17:55
  • Does this answer your question? [Passing variables, creating instances, self, The mechanics and usage of classes: need explanation](https://stackoverflow.com/questions/11421659/passing-variables-creating-instances-self-the-mechanics-and-usage-of-classes) – snatchysquid Jun 03 '20 at 17:58
  • What do you mean exactly? Please show an example of the usage you're trying to achieve. The snippet you posted doesn't make any sense, as @Carcigenicate pointed out. You can [edit] the question. Check out [ask] for tips if you want. – wjandrea Jun 03 '20 at 18:11

2 Answers2

0

You can pass arguements through the __init__ method of a class. Don't foget to set the first arguement to self. Also note calsses aren't defined like functions, you should use class instead of def.

EDIT After quick googling it seems like your question has been answered here.

snatchysquid
  • 1,283
  • 9
  • 24
  • I'm not sure what OP's trying to do, but this doesn't sound like it. `__init__` doesn't normally set class attributes. – wjandrea Jun 03 '20 at 18:19
0

Yes. Classes are first-class objects, and the execution of a class statement can make use of function parameters.

def make_class(value):
     class Foo:
         class_variable = value
         @classmethod
         def printVariable(cls):
             print(cls.class_variable)
     return Foo

Foo3 = make_class(3)
Foo3.printVariable()  # outputs 3

You can also call type directly.

def make_class(value):
    def printVariable(cls):
        print(cls.class_variable)

    return type('Foo', (), {'class_variable': value, 'printVariable': classmethod(printVariable)})

You also can do this without any function:

v = 3

class Foo:
    class_variable = v

    @classmethod
    def printVariable(cls):
        print(cls.class_variable)

v = 9

Foo.printVariable()  # outputs 3, not 9

When the class statement is executed, it uses the value of v at that time to initialize the class attribute class_variable; it does not save the name v and wait until you want to see the value of class_variable before looking up v.

chepner
  • 497,756
  • 71
  • 530
  • 681