I'd like to define a class inside a function (for testing purpose) and put a value into
a function variable:
def foo():
myvar = None
class myclass:
def run(self):
myvar = 5
mm = myclass()
mm.run()
print(myvar)
The above prints None
Is there any way other than global to make the myvar variable accessible from the class? The correct answer would print 5
It's not possible to assign a value to a variable outside the current scope without global. If you need to persist the value within the class you can define class variables instead. Example:
def foo():
class Class:
var_to_change = None
def run (self):
self.var_to_change = 5
print (Class.var_to_change)
instance = Class()
instance.run()
print (Class.var_to_change)
I haven't tested the above code but it should work in theory.
Related
Goal: Being able to access a in play.
Note: I need to save information via variables in the same instance of the class because play will be called multiple times.
Code:
class something():
def __init__(self):
a = 2
def play(self, b):
return True if a == b else False
test = something()
print(test.play(1))
Expectations: It should print False because 2 != 1, but I get this error instead:
UnboundLocalError: local variable 'a' referenced before assignment
I've tried:
Getting rid of __init__ and just putting the int outside a def.
Setting up the int before __init__ and just accessing it in __init__.
Note: I can't pass arguments to __init__ while making a new instance of the class, this is for an exercise, which can be found here, and I don't control the creation of a new instance.
class something():
def __init__(self):
self.a = 2
def play(self, b):
return True if self.a == b else False
test = something()
print(test.play(1))
In the __init__ you have to use self.variable and same can be used in other functions too of same class.
In a code, there is a class that has a function named 'goal_callback'. In the function, variables are defined using .init prefix and others are defined normally without the prefix.
I know that the self. prefix is used to make the variable a 'class variable' so that it can be accessible to every function in class. So in the code, I have, only one function present, does it make any difference if we define the variables with the self. prefix or not.
What exactly will be the difference between the '_pub_takeoff' variable and the 'takeoff_or_land' variable?
#! /usr/bin/env python
class CustomActionMsgClass(object):
def __init__(self):
self._as = actionlib.SimpleActionServer("action_custom_msg_as", CustomActionMsgAction,
self.goal_callback, False)
def goal_callback(self, goal):
success = True
r = rospy.Rate(1)
self._pub_takeoff = rospy.Publisher('/drone/takeoff', Empty, queue_size=1)
self._takeoff_msg = Empty()
self._land_msg = Empty()
# Get the goal word: UP or DOWN
takeoff_or_land = goal.goal #goal has attribute named 'goal'.
if __name__ == '__main__':
rospy.init_node('action_custom_msg')
CustomActionMsgClass()
rospy.spin()
Here is an example for object-level and class-level variables.
class A(object):
Z = 3 # class variable. Upper-case is good code style for class-level variables
# defined inside the class but outsize of it's methods
def __init__(self):
self.x = 1 # object variable
y = 2 # local variable; it will lost after returning from the function
def some_method(self):
self.w = 4 # object variable too
# Note that it is not recommended to define
# object variables outside of __init__()
In your code _pub_takeoff is variable of the object; takeoff_or_land is local variable.
I want to learn basics of classes in Python and got stuck. I declared same name of class variables and instance variable so that I could understand difference better but when I am using class variable inside the class methods it is showing error like NameError: global name 'a' is not defined. Can someone please tell me how to declare class variable inside and outside the class if both class variables and instance variables have same name. Code is given below and so error in output
class abc:
a=10
def __init__(self,a):
self.a=a
def mod1(self):
global a
a=5
self.a=105
def mod2(self):
a=15
self.a=110
def read(self):
print(self.a)
print(a)
b=abc(20)
print(b.a)
b.read()
b.mod1()
b.read()
b.mod2()
b.read()
Error is
20
20
Traceback (most recent call last):
File "/Users/rituagrawal/PycharmProjects/untitled2/code/garbage.py", line 18, in <module>
b.read()
File "/Users/rituagrawal/PycharmProjects/untitled2/code/garbage.py", line 14, in read
print(a)
NameError: global name 'a' is not defined
Process finished with exit code 1
Attributes set at the class level are shared by every instance of the class.
Attributes set on the instance in __init__ or other methods - for example self.a = a - are different for every instance, and available in every method.
References can also be set within a method - a = 15 - and these are only in scope within the method. print(a) within your read() method fails because no a has been set in that method.
Update:
Some code to illustrate.
class MyClass:
a = 10
def __init__(self, b):
self.b = b
def read(self):
c = 99
print(self.a) # Class attribute - the same for all instances of MyClass
print(self.b) # Instance attribute - each instance of MyClass has it's own, available in all methods
print(c) # Local - only available in this method.
Welcome to SO Ritu Agrawal.
self.a
is an instance variable, as you seem to have surmized. If you want to refer to the static (class) variable a, then you should use:
abc.a
So:
class abc:
a=10
def __init__(self,a):
self.a=a
abc.a = 40
b=abc(20)
print(b.a)
print(abc.a)
You can also use the __class__ member of an instance, so:
class abc:
a=10
def __init__(self,a):
self.a=a
__class__.a = 40
b=abc(20)
print(b.a)
print(b.__class__.a)
To begin with, I simplified your class as follows.
Here a, the class variable, is referenced inside the class functions using abc.a.
The a which is the instance variable is referenced using self.a
class abc:
a=5
def __init__(self,a):
self.a=a
def set(self, class_a, instance_a):
abc.a=class_a
self.a=instance_a
def read(self):
print(abc.a)
print(self.a)
Then, we start by defining the class and trying to read both variables. Class variable is still 5, and instance variable is 20
b=abc(20)
b.read()
#5
#20
Then, I set both class and instance variable a and try to read them. Class variable is changed to 30, and instance variable is changed to 60
b.set(30, 60)
b.read()
#30
#60
We can also directly access both variables outside the class using instance_object.a for instance variable and ClassName.a for class variable.
print(b.a)
#30
print(abc.a)
#60
Here is my code:
class MyClass:
def __init__(self):
self.value = 0
def set_value(self, value):
self.value = 5
def get_value(self):
return self.value
value = print("Hello")
a = MyClass()
The output is:
Hello
What I do not understand is why print("Hello") gets executed. When I create an instance of the class only the instance variable is set to 0. Why self.value = 0 calls value = print("Hello")?
Can someone explain me this behavior?
The code evaluates the class when you execute it, and calls the print to define the class variable value.
The below example shows that it's printed before the instanciation.
class MyClass:
def __init__(self):
self.value = 0
def set_value(self, value):
self.value = 5
def get_value(self):
return self.value
value = print("Hello")
print('hi')
a = MyClass()
#output
>>> Hello
>>>hi
It doesn't. That print is executed because it's at the class level itself; the body of a class is executed at the time the class is defined. You would get that output even if you never instantiated MyClass.
Don't let the indentation trick you. value is not an instance variable. value is a class variable because it is defined in the class's scope. It's the same as doing:
class MyClass:
value = print("Hello")
....
Which means that the call to print will run at class definition time. In other words, when Python defines MyClass it also defines all of the class level variables - including value. To define value, it then calls print, which is why Hello is printed before you create an instance of MyClass.
If you want only instances of MyClass to print Hello, put the variable definition inside of the class constructor.
Side note: The print function returns None, so it's seems a bit strange that your assigning the value to a variable. Perhaps you were looking for something like input instead?
It does not, drop a = MyClass() and it will print "Hello" anyway. It executes code in the body when a class is defined:
class MyClass:
print(2 * 2)
# prints 4
I am new to Python, and I am facing a problem:
def a(): ....
class b :
def c():
x=a()
My function a is defined outside of the class, and I need it to access inside the class in function c. How should I do this?
Just call it using a(), it's available through the global module scope:
def a():
return "test"
class b:
def c(self):
x = a()
print x
b().c() # prints "test"
Also see this thread: Short Description of the Scoping Rules?