the code:
class ceshi():
def one(self):
global a
a = "i m a"
def two(self):
print(a)
if __name__ == '__main__':
ceshi().two()
error message:
NameError: name 'a' is not defined
Didn't I define "a"? why the error message is 'name "a" is not defind'
You never actually define a. Just because you have it within function one does not mean that this function will be called.
You should either move a out of the class scope:
a = "i m a"
class ceshi():
def one(self):
# some other code
def two(self):
print(a)
or make a call to one() before calling two(), in order to define a.
if __name__ == '__main__':
ceshi().one()
ceshi().two()
"a" is only defined inside def one(), so you should declare it outside the method scope and later on define its value inside def one() if that's what you want to do. You could just leave it inside def one() but if the method isn't called, it still won't work.
So your code should look like:
class ceshi():
global a
def one(self):
a = "i m a"
def two(self):
print(a)
class TestGlobal():
def one(self):
global a
a = "i m a"
def two(self):
global a
print(a)
or you can write this way
class TestGlobal():
global a
def __init__(self):
self.a = self.one()
def one(self):
self.a = "i m a 5"
def two(self):
print('------------------>',self.a)
when you defining any variable in class and method then it consider for particular class or method. So if it is global variable then call it as global first then used it.
Related
I have class
class A:
def __init__(self):
print(i was used by :)
# if i call this class from the function below,
def my_func():
a = A()
# I need class A to print that "i was used in: my_func() "
Is there any solution for this ?
If you know the function name:
You could try something like:
class A:
def __init__(self, func):
print('i was used by:', func.__name__)
def my_func(func):
a = A(func)
my_func(my_func)
Output:
i was used by: my_func
This you would specify the function instance, which is the most optimal way here, then just use the __name__ to get the name of the function.
If you don't know the function name:
You could try the inspect module:
import inspect
class A:
def __init__(self):
print('i was used by:', inspect.currentframe().f_back.f_code.co_name)
def my_func():
a = A()
my_func()
Or try this:
import inspect
class A:
def __init__(self):
cur = inspect.currentframe()
a = inspect.getouterframes(cur, 2)[1][3]
print('i was used by:', a)
def my_func():
a = A()
my_func()
Both output:
i was used by: my_func
How to use variable outside of function which is define inside of function?
And Function should declare in class.
class A:
def aFunction(self):
aVariable = "Hello"
Now here I want to use that aVariable
If you want to use this variable within the class A, how about using an instance variable?
class A:
def aFunction(self):
self.aVariable = "Hello"
Now you can use self.aVariable in another function of the same class
There are definitely more options that maybe others will provide, but these are the options I have come up with.
Use return
class A:
def aFunction(self):
aVariable = "Hello"
return aVariable
obj = A()
var = obj.aFunction()
print(var)
use global
class A:
def aFunction(self):
global aVariable
aVariable = "Hello"
obj = A()
obj.aFunction()
print(aVariable)
You can use self to your advantage
class A:
def __init__(self):
self.aVariable = None
def aFunction(self):
self.aVariable = "Hello"
obj = A()
obj.aFunction()
print(obj.aVariable)
To use a variable from a class outside of the function or entire class:
class A:
def aFunction(self):
self.aVariable = 1
def anotherFunction(self):
self.aVariable += 1
a = A() # create instance of the class
a.aFunction() # run the method aFunction to create the variable
print(a.aVariable) # print the variable
a.anotherFunction() # change the variable with anotherFunction
print(a.aVariable) # print the new value
There are several methods you can try.
class A:
def aFunction(self):
self.aVariable = "Hello"
# you can access self.aVariable in the class
class A:
def aFunction(self):
aVariable = "Hello"
return aVariable
# use self.aFunction() whenever you need this variable
The return keyword will return the value provided. Here, you have provided self.aVariable. Then, you can assign the value to a variable outside the class and print the variable.
class A:
def aFunction(self):
self.aVariable = "Hello"
return self.aVariable
a = A() #==== Instantiate the class
f=a.aFunction() #==== Call the function.
print(f)
This will print: Hello
How I can call a function inside class like this code? I tried, but I can not... The idea is: I want update the other function inside de class, than I use this code, without sucess: app=MyApp() app.build.last1.text=time.strftime("%H:%M:%S \n")
How I do it?
(...)
class PL1_detect(Button):
def update(self, dt):
global ModoPisca
global t
global ModoPisca2
global last2
#ModoPisca=0
def tpisca():
conta=0
global estado_PTT1
##clock(self, dt)
app=MyApp()
app.build.last1.text=time.strftime("%H:%M:%S \n")
#(here the problem: HOW I CAN CALL FUNCTION OF CLASS
MYAPP(APP) ????
(...)
class MyApp(App):
def build(self):
layout = FloatLayout(size=(800, 600))
# Make the background gray:
with layout.canvas.before:
Color(.2,.2,.2,1)
self.rect = Rectangle(size=(800,600), pos=layout.pos)
wimg = Image(source='logo.png', pos=(0,180))
last1=Label(text=(" "), pos=(-330, -110), font_size='17sp', bold=0)
return layout
if __name__ == '__main__':
MyApp().run()
You can create object for that class
M=Myapp()
M.build() will help in calling that function.
Try this for your scenario
class A():
def funct1(self):
sample="hi"
class B():
def func2(self):
A.sample="hello"
print A.sample
a=A()
a.funct1()
b=B()
b.func2()
Output:
hello
This question already has answers here:
How can I access variables from the caller, even if it isn't an enclosing scope (i.e., implement dynamic scoping)?
(4 answers)
Closed 6 months ago.
I want to do this (dummy example):
def func():
nonlocal var
print (var)
class A:
var = 'hola'
func()
But I get: "SyntaxError: no binding for nonlocal 'var' found"
What I really intend to do is append a method name to a list in the scope of the class if that method is decorated. Something like this:
def decorator(func):
nonlocal decorated
decorated.append(func.__name__)
return func
class A:
decorated = []
#decorate
def f(self):
pass
Python just doesn't let you do this. You can access the class namespace by using locals(). But at this point, you might as well just pass the variable you're interested in to the decorator.
# using locals()
def decorator(class_namespace):
def _decorator(func):
class_namespace["decorated"].append(func)
return func
return _decorator
class A:
store = decorator(locals())
decorated = []
#store
def func(self):
pass
del store
Generally, it's easy to use a pair of decorators. One to mark the functions you're interested in, and one to collect them.
from types import FunctionType
def collect(cls):
for item in vars(cls).values():
print(item)
if isinstance(item, FunctionType) and getattr(item, "marked", False):
cls.marked_funcs.append(item)
return cls
def mark(func):
func.marked = True
return func
#collect
class B:
marked_funcs = []
#mark
def func(self):
pass
But in your case it might just be simpler to create the set of function names at the end of the class. eg.
class C:
def func(self):
pass
func_names = [f.__name__ for f in [func]]
Use the decorator to mark the functions, then have decorated be a class method which returns all decorated functions.
import inspect
def decorate(func):
func.decorated = True
return func
class A:
def foo():
print('foo')
#decorate
def bar():
print('bar')
#classmethod
def decorated(cls):
def is_decorated_method(obj):
try:
return inspect.isfunction(obj) and obj.decorated
except AttributeError:
# The object has no decorated attribute
return False
return [result[1] for result in inspect.getmembers(cls, predicate=is_decorated_method)]
print(A.decorated())
# [<function A.bar at 0x6ffffc0aa60>]
y = 20
def f():
x = 7
def g():
nonlocal x # 7
global y # 20
nonlocal qualifier refers to a name in the outer function scope, which does not include the module scope. While global does the complementary. So you are using nonlocal incorrectly.
How about that?
decorated = []
def decorator(func):
decorated.append(func.__name__)
def wrapper(self):
print('wrapper called')
func(self)
return wrapper
class A:
#decorator
def f(self): print('function called')
print(decorated)
A().f()
OUTPUT:
['f']
wrapper called
function called
NOTES:
The code you provided experiencing the issue you've described because var is class variable so it must be referenced as A.var but you cannot do that in your code because you try to use it before A is defined. if it were different classes it would be possible:
class X:
decorated = []
def decorator(func):
X.decorated.append(func.__name__)
return func
class A:
#decorator
def f(self):
pass
print(X.decorated)
Please note that you don't need to specify nonlocal if you don't assign to variable but call methods like append().
there is a way to pass a value or a variable from a class to another class without having to pass through the main function
I'm using python
well, of course you can access other objects attributes in methods of a specific object. e.g:
class A(object):
def method(self, other):
other.somevar = 5
class B(object):
pass
def main():
a = A()
b = B()
b.somevar = "Hello World"
a.method(b)
print(b.somevar) # now prints '5'