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()
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 would like to use functions based on strings passed in argument as below. The code gives the following error: AttributeError: 'Obj' object has no attribute 'funA'
The functions funA and funB are defined within fun because they are only used within fun and nowhere else
class Obj(object):
def __init__(self):
self.A = 2
self.B = 3
def fun(self, ar):
def funA(self):
print self.A
def funB(self):
x = self.B + 4
print self.B
for letter in ar:
name = 'fun' + letter
getattr(self, name)()
obj_instance = Obj()
obj_instance.fun(['A', 'B'])
As an alternative you can try the following code. It gives you the opportunity to check whether a function exists or not.
class Obj(object):
def __init__(self):
self.A = 2
self.B = 3
def fun(self, ar):
def funA():
print self.A
def funB():
x = self.B + 4
print self.B
print x
for letter in ar:
name = 'fun' + letter
if name in locals():
locals()[name]()
obj_instance = Obj()
obj_instance.fun(['A', 'B'])
I wouldn't recommend it, but if you really need it, then you can do it this way:
class Obj(object):
def __init__(self):
self.A = 2
self.B = 3
def fun(self, ar):
def funA(self):
print self.A
def funB(self):
x = self.B + 4
print self.B
for letter in ar:
name = 'fun' + letter + '()'
exec(name)
obj_instance=Obj()
obj_instance.fun(['A', 'B'])
exec() executes any string that you put in parentheses as if it was python code.
I am working through reviewing a video on Lynda and sometimes instead of just running the provided code I typed it myself.
The instructor's code works, but mine doesn't.
It returns "object does not take parameters".
Mine is on top, his is on the bottom.
Can anyone explain?
class Fibonnacci():
def _init_(self, a, b):
self.a = a
self.b = b
def series(self):
while(True):
yield(self.b)
self.a, self.b = self.b, self.a + self.b
f = Fibonnacci(0, 1)
for r in f.series():
if r > 100: break
print(r, end=' ')
class Fibonacci():
def __init__(self, a, b):
self.a = a
self.b = b
def series(self):
while(True):
yield(self.b)
self.a, self.b = self.b, self.a + self.b
f = Fibonacci(0, 1)
for r in f.series():
if r > 100: break
print(r, end=' ')
The reason is the init function in the class. The way this method works as seen here to let an object be assigned parameters when initialized. I am sure you understand this, but the simple error you made was that it requires 2 underscores on either side to take effect. Like this: __init__. That is the difference between your two codes.
class Fibonnacci():
def _init_(self, a, b): #<-- the error is here, should be __init__()
self.a = a
self.b = b
def series(self):
while(True):
yield(self.b)
self.a, self.b = self.b, self.a + self.b
f = Fibonnacci(0, 1)
for r in f.series():
if r > 100: break
print(r, end=' ')
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 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()