How to access a function defined globaly outside of the class - python

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?

Related

See function stop from locating defined class in Python

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.

What is difference between defining variable inside __init__ function and outside the function

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

How does python deal with this inheritance issue?

class A:
def __init__(self):
print('I am A')
class B(A):
def b(self):
print('I am B.b')
class C(A):
def c(self):
x.b()
if __name__ == '__main__':
x = B()
y = C()
y.c()
How does it work when it comes to 'y.c() '?
In C.c(), how can the instance x be called without instantiation before?
Thanks a lot, if someone can help.
It cannot. In your case, it just happens that when you call x.b() there is a global variable that happens to be named x have type B. It has been initialized at the previous line, with x = B().
This code depends on external variables, and will fail in general. If you want to call the objects own method, use self.b() instead.

Defined method is not defined inside class [duplicate]

This question already has answers here:
How can I call a function within a class?
(2 answers)
Closed 4 years ago.
I am relatively new to python and i am experiencing some issues with namespacing.
class a:
def abc(self):
print "haha"
def test(self):
abc()
b = a()
b.test() #throws an error of abc is not defined. cannot explain why is this so
Since test() doesn't know who is abc, that msg NameError: global name 'abc' is not defined you see should happen when you invoke b.test() (calling b.abc() is fine), change it to:
class a:
def abc(self):
print "haha"
def test(self):
self.abc()
# abc()
b = a()
b.abc() # 'haha' is printed
b.test() # 'haha' is printed
In order to call method from the same class, you need the self keyword.
class a:
def abc(self):
print "haha"
def test(self):
self.abc() // will look for abc method in 'a' class
Without the self keyword, python is looking for the abc method in the global scope, that is why you are getting this error.

Python define class in function, the class canbe access global

abc.py, how to create b() in class a ?
class a(object):
bInst=b()
def start():
class b(obj):
pass
if __name=='__main__'
start()
But how to using variable, Here is the codes, it report 'myCls' is not defined.
class a(obj):
inst=myCls()
def start
tSuiteN="myCls"
exec('global tSuiteN')
str="class {}(object): pass".format(tSuiteN)
exec(str)
Make it global.
def start():
global b
class b(obj):
pass

Categories

Resources