Python define class in function, the class canbe access global - python

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

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.

Python:Error calling class variable in a staticmethod

I am trying to call a class variable within a staticmethod, but when I called I am getting an error "hello" is not defined. any advise ?
class hello:
random1 = []
#staticmethod
def sub(x):
hello.random1.append(x -1)
sub.__func__(2)
if __name__ == "__main__":
print(hello.random1)
hello doesn't exist as a global name until you dedent out of the class definition (at which point the class is created and assigned to the global name hello). Change the code to:
class hello:
random1 = []
#staticmethod
def sub(x):
hello.random1.append(x -1)
hello.sub(2)
so sub is invoked after hello exists, and it will work.

Can I control the function to call written in the __init__ function?

I want to know if there is a way to control the function call written in the __init__ function of a class ? on an existing framework they have written two function calls inside the __init__ function but I want to call only one, say the first one only. Can I achieve this using Python?
def funA():
print('calling functionA()')
def funB():
print('calling functionB()')
class A():
def __init__(self):
a = funA()
b = funB()
c = A()
Assume I want to call only funA and not B. Can I do that?
I tried referring to the other thead which can skip the __init__ part using helper class, but that does not seem to help me.
Please advise.
You can define a class, which uses A as parent class and overrides its __init__() method as follows:
def funA():
print('calling functionA()')
def funB():
print('calling functionB()')
class A():
def __init__(self):
a = funA()
b = funB()
def othermet(self):
print('calling method of parent class')
class M(A):
def __init__(self):
a = funA()
c = M()
c.othermet()
Out:
calling functionA()
calling method of parent class

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 to access a function defined globaly outside of the class

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?

Categories

Resources