How to access variable outside class in my example? - python

class testing():
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def house(self):
d = self.a+self.b+self.c
print d
module="hello"
p = testing(1, 2, 3)
p.house()
How do I access module variable from within my testing class? I know I could just add it as a parameter to the class constructor by doing:
p=testing(1,2,3,module)
But I don't want to do that unless I have to. What other ways can I access module variable from inside the testing class?

You simply reference it; you don't need any special global permission to access it. This isn't the best way, but since you haven't described your application and modularity requirements, about all we can do right now is to solve your immediate problem.
By the way, your a, b, c references are incorrect. See below.
class testing():
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
self.greeting = module
def house(self):
d = self.a + self.b + self.c
print d
print self.greeting
module="hello"
p = testing(1, 2, 3)
p.house()
Output:
6
hello

You could use globals(). But I'm not sure if this is good idea at all.
class testing():
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def house(self):
print(globals()['module'])
d = self.a + self.b + self.c
print(d)
module = 'here'
t = testing(1, 2, 3)
t.house()
Output:
# here
# 6

Maybe I don't understand the question, it already works since the global variable "module" is defined before you instantiated the class.
class testing():
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def house(self):
d = self.a+self.b+self.c
print module
print d
module="hello"
p = testing(1, 2, 3)
p.house()
outputs:
hello
6

Related

How to define a variable of a class as class object in Python

I need to define a variable of a class a class object. How can I do it?
if for example I have a class like this :
class A:
def __init__(self, a, b):
self.a = a
self.b = b
and I want to create another class B that have a variable as instance of class A like :
class B:
def __init__(self, c = A(), d):
self.c = c
self.d = d
How can I do it ? I need to do particular operation or simply declarate c as object of class A when I create the object of class B ?
class B:
def __init__(self, a, b, d):
self.c = A(a, b)
self.d = d
or
class B:
def __init__(self, c, d):
self.c = c
self.d = d
or
class B:
def __init__(self, d):
self.c = A(a, b) # a and b can be values
self.d = d
What you wrote mostly works:
def __init__(self, c = A(), d):
self.c = c
But there's a "gotcha" which you really want to avoid.
The A constructor will be evaluated just once,
at def time, rather than each time you construct
a new B object.
That's typically not what a novice coder wants.
That signature mentions a mutable default arg,
something it's usually best to avoid,
if only to save future maintainers from
doing some frustrating debugging.
https://dollardhingra.com/blog/python-mutable-default-arguments/
https://towardsdatascience.com/python-pitfall-mutable-default-arguments-9385e8265422
Instead, phrase it this way:
class B:
def __init__(self, c = None, d):
self.c = A(1, 2) if c is None else c
...
That way the A constructor will be evaluated afresh each time.
(Also, it would be good to supply both of A's mandatory arguments.)

UnboundLocalError: local variable 'd' referenced before assignment

I am trying to access a variable from static method to outside.
class Hello():
def __init__(self, a, b):
self.a = a
self.b = b
self.c = 0
#staticmethod
def add():
d = 10
print("hello", d)
How to access variable 'd' in outside of static method?
First of all, you don't need #staticmethod for just d = 10. You can assign it outside of the constructor (as mentioned below). And then to access that variable, you can try, CLASS_NAME.VARIABLE_NAME.
class Hello():
d = 10
def __init__(self, a, b):
self.a = a
self.b = b
self.c = 0
print("hello", Hello.d)

How can I sum up the values of two functions?

I have two classes. In class B I want to change the values of the variables in class A, which are defined in functions: some and anyt, with the help of the functions in class B: frog and lion.
For example, I multiply by 2 or 3..
I get the Error:
File "E:/Python/Akustik/Akustik/Test.py", line 20
A.some(a,b,c) = A.some(a,b,c)* 2
^
SyntaxError: can't assign to function call
I know what does that mean, but i can't dispense with the functions in class A and B, does anybody have a tip?
here is the code:
class A:
def some(self,a, b, c):
self.a = 4
self.b = 2
self.c = 3
def anyt(self, p, g, f):
self.p = 5
self.g = 8
self.f = 1
class B(A):
def frog(self):
A.some(a,b,c) = A.some(a,b,c)* 2
def lion(self):
A.anyt(p,g,f)= A.anyt(p,g,f) * 3
You cannot assign the value of an expression to a function call. In your case if you want to change the value of variables a, b, c, p, q, r. You will have to do something like this.
class A:
def __init__(self):
self.a = 1
self.b = 1
self.c = 1
self.p = 1
self.q = 1
self.r = 1
def some(self,a, b, c):
self.a = a
self.b = b
self.c = c
def anyt(self, p, g, f):
self.p = p
self.g = g
self.f = f
class B(A):
def frog(self):
self.some(self.a*2, self.b*2, self.c*2)
def lion(self):
self.anyt(self.p*3, self.g*3, self.f*3)
b = B()
b.frog()
print(b.c)
# Prints current value of c
This ensures the corresponding variable values change.

NameError: name 'addition' is not defined

I am getting NameError: name 'addition' is not defined while running following code
class Arithmetic:
def __init__(self, a, b):
self.a = a
self.b = b
def addition(self):
c = a + b
print"%d" %c
def subtraction(self):
c=a-b
print "%d" % c
add = addition(5, 4)
add.addition()
If you want to use your 'addition' method, you first need to instantiate an Arithmetic() object and use dot notation to call their functions. Make sure you properly indent your code because not only is it breaking a lot of PEP 8 rules but it just looks plain messy. In your first definition, don't forget you have to type __init__ not init. Here's the code which should be applied:
class Arithmetic(object):
def __init__(self, a, b):
self.a = a
self.b = b
def addition(self):
c = self.a + self.b
print c
def subtraction(self):
c = self.a - self.b
print c
a = Arithmetic(5, 4)
a.addition()
a.subtraction()
You first have to create object of class and then you can access class function.
Try this:
a = Arithmatic()
a.addition(5,4)
Check out this piece of code:
class Arithmetic():
def init(self, a, b):
self.a = a
self.b = b
def addition(self):
c = self.a + self.b
print"addition %d" %c
def subtraction(self):
c = self.a - self.b
print"substraction %d" %c
obj = Arithmetic()
obj.init(5, 4)
obj.addition()
obj.subtraction()

how to create local dynamic variables

this is my code, I want to use eval() to get the rule status but eval() needs local variables, there is many classes that inherits the base class, so I need to rewrite get_stat() in every class.
I want to avoid this, an idea is to create dynamic variables in get_stat(),eg. class b dynamically creates variables a and b in func get_stat()
How should I create dynamic varables in function? or any other way to avoid this stupid idea. I use python 3.2.3, locals() does not work
class base(object):
def check(self):
stat = get_stat()
def get_stat(self):
pass
class b(base):
rule = 'a > 5 and b < 3'
a = 0
b = 0
def update_data(self, a, b):
self.a = a
self.b = b
def get_stat(self):
a = self.a
b = self.b
return eval(rule)
class b(base):
rule = 'd > 5 and e < 3'
d = 0
e = 0
def update_data(self, d, e):
self.d = d
self.e = e
def get_stat(self):
d = self.d
e = self.e
return eval(rule)
You can pass a dictionary to the eval() function containing the variables to evaluate the expression against:
>>> eval("a + b", {"a": 2, "b": 3})
5
Pass self.__dict__ to give access to an object's attributes:
>>> class MyClass(object):
... def __init__(self):
... self.a = 2
... self.b = 3
...
>>> obj = MyClass()
>>> obj.__dict__
{'a': 2, 'b': 3}
>>> eval("a + b", obj.__dict__)
5
Links:
eval
__dict__

Categories

Resources