How to Access Class Member Variables in Python

How do I access Class member variables?

The answer, in a few words

In your example, itsProblem is a local variable.

Your must use self to set and get instance variables. You can set it in the __init__ method. Then your code would be:

class Example(object):
def __init__(self):
self.itsProblem = "problem"

theExample = Example()
print(theExample.itsProblem)

But if you want a true class variable, then use the class name directly:

class Example(object):
itsProblem = "problem"

theExample = Example()
print(theExample.itsProblem)
print (Example.itsProblem)

But be careful with this one, as theExample.itsProblem is automatically set to be equal to Example.itsProblem, but is not the same variable at all and can be changed independently.

Some explanations

In Python, variables can be created dynamically. Therefore, you can do the following:

class Example(object):
pass

Example.itsProblem = "problem"

e = Example()
e.itsSecondProblem = "problem"

print Example.itsProblem == e.itsSecondProblem

prints

True

Therefore, that's exactly what you do with the previous examples.

Indeed, in Python we use self as this, but it's a bit more than that. self is the the first argument to any object method because the first argument is always the object reference. This is automatic, whether you call it self or not.

Which means you can do:

class Example(object):
def __init__(self):
self.itsProblem = "problem"

theExample = Example()
print(theExample.itsProblem)

or:

class Example(object):
def __init__(my_super_self):
my_super_self.itsProblem = "problem"

theExample = Example()
print(theExample.itsProblem)

It's exactly the same. The first argument of ANY object method is the current object, we only call it self as a convention. And you add just a variable to this object, the same way you would do it from outside.

Now, about the class variables.

When you do:

class Example(object):
itsProblem = "problem"

theExample = Example()
print(theExample.itsProblem)

You'll notice we first set a class variable, then we access an object (instance) variable. We never set this object variable but it works, how is that possible?

Well, Python tries to get first the object variable, but if it can't find it, will give you the class variable. Warning: the class variable is shared among instances, and the object variable is not.

As a conclusion, never use class variables to set default values to object variables. Use __init__ for that.

Eventually, you will learn that Python classes are instances and therefore objects themselves, which gives new insight to understanding the above. Come back and read this again later, once you realize that.

How to access class variable inside methods of that class in python?

There are two ways to access it

first: self.__class__.PAD_token

second: self.PAD_token

If you just need to access class variables, the first one is recommended

How would I access variables from one class to another?

var1 and var2 are instance variables. That means that you have to send the instance of ClassA to ClassB in order for ClassB to access it, i.e:

class ClassA(object):
def __init__(self):
self.var1 = 1
self.var2 = 2

def methodA(self):
self.var1 = self.var1 + self.var2
return self.var1

class ClassB(ClassA):
def __init__(self, class_a):
self.var1 = class_a.var1
self.var2 = class_a.var2

object1 = ClassA()
sum = object1.methodA()
object2 = ClassB(object1)
print sum

On the other hand - if you were to use class variables, you could access var1 and var2 without sending object1 as a parameter to ClassB.

class ClassA(object):
var1 = 0
var2 = 0
def __init__(self):
ClassA.var1 = 1
ClassA.var2 = 2

def methodA(self):
ClassA.var1 = ClassA.var1 + ClassA.var2
return ClassA.var1

class ClassB(ClassA):
def __init__(self):
print ClassA.var1
print ClassA.var2

object1 = ClassA()
sum = object1.methodA()
object2 = ClassB()
print sum

Note, however, that class variables are shared among all instances of its class.

Access class variable from function in Python

eaten should be a instance variable, not a class variable - you can have some players eaten and others not, and having it as a class variable means it would affect all players, which is probably not what you want.

class Player(object):
def __init__(self):
self.eaten = False

def move(self):
if self.eaten:
print("I have eaten so I can move")
else:
print("I can't move! I'm hungry!")

def eat(player, food):
player.eaten = True # change `eaten` for the player
# passed as parameter!

>>> p = Player() # creates a instance of the Player class
>>> q = Player() # creates another instance of the Player class
>>> eat(p, 'apple') # player `p` eates apple
>>> p.move()
I have eaten so I can move
>>> q.move()
I can't move! I'm hungry!

print(p.eaten) # will print True
print(q.eaten) # will print False

Best way to access class member in a class in Python

You should access a class variable only by class name, since that variable is shared among all classes. Thus, to avoid confusion, one should only access class variables by the name of the class; otherwise it might lead to surprising errors (See the second snippet).

How can I access static class variables within methods?

Instead of bar use self.bar or Foo.bar. Assigning to Foo.bar will create a static variable, and assigning to self.bar will create an instance variable.

Accessing class variable based on user input

Yes it's possible, you can use the builtin function getattr like this:

print(getattr(test.fields, random))

Can I access class variables using self?

Assigning remote to self in __init__ means that instance.remote is found first when you access it through self (granted no descriptors are around). To get both options, access either from self or from type(self), that is, either from the instance or the class:

def print_remote(self):
print(type(self).remote) # class remote
print(self.remote) # instance remote

type(self).remote is essentially equivalent to self.__class__.remote but, in general, you should avoid grabbing dunder names (__*__) when there's a built in that does it for you (type in this case)

These live in different dictionaries and are different variables. self.remote lives in the instance dict while class.remote in the class dict.

>>> Foo().__dict__['remote']
True
>>> Foo.__dict__['remote']
False

When you access through cls with a classmethod (or type(self) in a normal method) you'll get the class one, when you access through self you get the instance one.

Accessing member variable in Python?

To refer to class attributes within the class methods you need pass the object itself into the methods with the keyword self. Then you can access other class methods and the class attributes with self.foo.

Also, the while True loop should not be indented at root level within the class. Last, the foo++ C-style is not correct in Pyhton, it should be foo += 1

how to access the class variable by string in Python?

To get the variable, you can do:

getattr(test, a_string)


Related Topics



Leave a reply



Submit