-1

Is there a way in Python to call class object from function definition ?

Let say I have class

class myClass():
          def __init__(self, member1 = 0)
          self.member1 = member1

and function definition

def myFunction(x):
    var1 = ............

I would like to assign member1 to var1 in function definition.

Thanks !

newprint
  • 6,596
  • 12
  • 62
  • 102

3 Answers3

3

Do you understand what classes are for?

You would like to assign member1 of which instance of the class to var1?

Is x supposed to be an instance of myClass that you're passing to myFunction? Then it's simple: var1 = x.member1.

Karl Knechtel
  • 56,349
  • 8
  • 83
  • 124
1

Sounds like you need member1 to be a static class variable. See Static class variables in Python.

Community
  • 1
  • 1
chrisaycock
  • 34,416
  • 14
  • 83
  • 119
1

Just do it:

class myClass():
    def __init__(self, member1 = 5):
        self.member1 = member1

def myFunction(x):
    var1 = myClass().member1
    print x, var1


myFunction(2)

prints 2 5

myClass class is global to the module so it can be seen inside the function.

joaquin
  • 78,380
  • 27
  • 136
  • 151
  • Well, you did not say you wanted to assign to myClass().member1 in your specification. Why to do that?. I would understand you want to assign a value to var1, or to member1 inside the class, or at class instantiation, even as myClass(1).member1... – joaquin Dec 06 '10 at 00:59