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__
Related
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)
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()
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
I am wondering if it is possible to initialize a class stored in a variable. For example:
class cl():
def __init(self, a):
self.a = a
return
def print(self):
print(self.a)
return a
In[27]: c = cl
In[28]: c
Out[28]: __main__.cl
and now I want to initialize cl with value of a=3
class cl():
def __init__(self, a):
self.a = a
def print_a(self):
print(self.a)
c = cl
c(3)
c.print_a()
>>> 3
Yes it is totally possible. When you do c = c1 it creates c as an exact alias of c1.
You then do
obj_from_c1 = c1()
obj_from_c c()
I am quite new with python, is there a way to construct a child class using a parent instance?
Well I was thinking about:
class A:
def __init__(self,a,b):
self.a = a
self.b = b
class B(A):
def __init__(self,A):
self.super = A
self.c = -1
def __init__(self,a,b,c):
super(a,b)
self.c = c
myA = A(1,2)
myB = B(myA)
So for having B objects I could use A objects to construct them.
This will do what you ask, and create a new B, using the data from an existing A, and then complete the initialisation of the new B:
class A(object):
def __init__(self, a, b):
self.a = a
self.b = b
def __str__(self):
return "A: a = %s, b = %s" % (self.a, self.b)
class B(A):
def __init__(self, *args):
if type(args[0]) is A:
self.__dict__ = args[0].__dict__.copy()
c = args[1]
else:
super(B, self).__init__(*args[:2])
c = args[2]
self.c = c
def __str__(self):
return "B: a = %s, b = %s, c = %s" % (self.a, self.b, self.c)
Usage:
myA = A(1, 2)
print myA
print B(3,4,5) # regular B
myB = B(myA, 10) # B created from an A
print myB
Output:
A: a = 1, b = 2
B: a = 3, b = 4, c = 5
B: a = 1, b = 2, c = 10
Note that the new instance doesn't get a new copy of the data, it gets a new set of references to that data. If a were a list and you did myA.a.append(value), then myB.a would also have value in it. If you want that not to be the case, change the assignment of __dict__ to:
self.__dict__ = deepcopy(args[0].__dict__)
Note: None of this won't work if you're using slots, because __dict__ won't exist
You can make use of the facts that:
class is an executable statement;
classes are first-class objects.
For example:
class A(object):
pass
def CreateB(superclass):
class subclass(superclass):
pass
return subclass
B = CreateB(A)
myA = A()
myB = B()
That said, it's not entirely clear to me what is the actual problem you are trying to solve.
In your example, methods in classes need a first argument to refer to themselves. Normally this is named self.
class A:
pass #class A code
class B(A):
def __init__(self, a):
self.super = a
myA = A()
myB = B(myA)
The code above will create a B instance with a reference to an A instance called super. If you want B to inherit from A then you would change the code slightly more.
class A:
pass #class A code
class B(A):
def __init__(self):
A.__init__(self)
myA = A()
myB = B()