I am new in Python and I wrote the following code:
class Frazione:
def __init__(self, Numeratore, Denominatore=1):
mcd=MCD(Numeratore,Denominatore)
self.Numeratore=Numeratore/mcd
self.Denominatore=Denominatore/mcd
def MCD(m,n):
if m%n==0:
return n
else:
return MCD(n,m%n)
def __str__(self):
return "%d/%d" %(self.Numeratore, self.Denominatore)
def __mul__(self, AltraFrazione):
if type(AltraFrazione)==type(5):
AltraFrazione=Frazione(AltraFrazione)
return Frazione(self.Numeratore*AltraFrazione.Numeratore, self.Denominatore*AltraFrazione.Denominatore)
__rmul__=__mul__
Open shell at the same folder of Frazione.py:
>>> from Frazione import Frazione
end then
>>> f=Frazione(10,5)
When I press Enter, I receive this output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File ".\Frazione.py", line 5, in __init__
mcd=MCD(Numeratore,Denominatore)
NameError: global name 'MCD' is not defined
PS. I apologize for my english!
MCD is a method of Frazione, but you're calling it as if it were a global function. The easiest (and cleanest, IMHO) fix is to just move it outside the class, because it doesn't need to access any class or instance members.
So:
def MCD(m, n):
if m % n == 0:
return n
else:
return MCD(n, m % n)
class Frazione:
# as before but without MCD
If you do want to keep it in the class, then you might rewrite it to be iterative instead of recursive and call it as self.MCD in __init__. That's a good idea anyway, as Python's support for recursion is rather weak.
Related
So, it says that create in line 11 is not defined, but it is a recursive function within the class. And In VS Code, it shows me an error at line 6 - it says that I am missing the self argument, but when I add it, it requires 3 arguments in line 23 (why, I can't provide an argument for self, can I ?)
I already tried it with various variations of adding self to the arguments, but nothing worked.
class smarray:
def __init__ (self):
self.array = []
def create(index, dim):
array1 = []
if index < len(dim)-1:
for x in range(0,dim[index]):
array1.append((create(index+1,dim)))
return array1
else:
for x in range(0,dim[index]):
array1.append("nul")
return array1
if index ==0:
self.array = array1
t = smarray()
t = smarray.create(0, [3,4])
error TB:
Traceback (most recent call last):
File "/Users/pc/Documents/VS Code Files/Python testing/testing range.py", line 23, in <module>
t = smarray.create(0, [3,4])
File "/Users/pc/Documents/VS Code Files/Python testing/testing range.py", line 11, in create
array1.append((create(index+1,dim)))
NameError: name 'create' is not defined
There are a couple of things needed to be fixed in order for this code snippet to run:
class smarray:
def __init__(self):
self.array = []
def create(self, index, dim):
array1 = []
if index < len(dim)-1:
for x in range(0, dim[index]):
array1.append((self.create(index+1, dim)))
return array1
else:
for x in range(0, dim[index]):
array1.append("nul")
return array1
if index == 0:
self.array = array1
t = smarray()
my_array = t.create(0, [3, 4])
So, the first fix would be adding the self keyword to the def create() method signature.
Second, in the line array1.append(...) the same self keyword had to be added, so we can call the create method properly: self.create()
And the last one I changed the call to the create method as "instance method" and not as "class method" - I hope I understood correctly what you tried to achieve here. You can read more here.
Pay attention that the last if index==0 is unreachable, thus the code self.array = array1 won't be ever executed. I don't quite sure what you were trying to achieve there.
I have a class :
class Difference:
def __init__(self,a1):
self.a1=a1
def computeDifference(self):
d0=max([max(self.a1)-i for i in self.a1])
return d0
maximumDifference=d0
Now when i try to access the class like bellow getting bellow error:
_ = input().strip()
a = [int(e) for e in input().strip().split(' ')]
d = Difference(a)
d.computeDifference()
print(d.maximumDifference)
error:
Traceback (most recent call last):
File "q.py", line 2, in
class Difference:
File "q.py", line 8, in Difference
maximumDifference=d0
NameError: name 'd0' is not defined
what went wrong?
A few things:
You need to define what d0 is before you can assign it to maximumDifference.
And even if you do define d0 and try to assign it to maximumDifference it won't be reached because that line is after the return statemen.
incorrect indentation but that might be just how you posted your question. I edited your question to fix the indentation error
you can do something like this to fix the above problems:
def computeDifference(self):
d0=max([max(self.a1)-i for i in self.a1])
self.maximumDifference=d0
return d0
The above code would work But it is NOT good practice to define attribute outside of __init__. It is better to define class attributes inside of __init__
class Difference:
def __init__(self,a1):
self.a1=a1
self.maximumDifference = self.computeDifference()
def computeDifference(self):
d0=max([max(self.a1)-i for i in self.a1])
return d0
Your problem is with indentation. Python code must be well indented in order to work properly. Try:
class Difference:
def __init__(self,a1):
self.a1=a1
def computeDifference(self):
d0=max([max(self.a1)-i for i in self.a1])
self.maximumDifference=d0
return d0
Also the line maximumDifference=d0 would never be reached as it was placed after a return and, even if it was, your code wouldn't work since you're using only locally. To store and use maximumDifference outside that function you should store it in self.maximumDifference like the example above.
I wrote a code which is going to store occurrences of words from a text file and store it to a dictionary:
class callDict(object):
def __init__(self):
self.invertedIndex = {}
then I write a method
def invertedIndex(self):
print self.invertedIndex.items()
and here is how I am calling:
if __name__ == "__main__":
c = callDict()
c.invertedIndex()
But it gives me the error:
Traceback (most recent call last):
File "E\Project\xyz.py", line 56, in <module>
c.invertedIndex()
TypeError: 'dict' object is not callable
How can I resolve this?
You are defining a method and an instance variable in your code, both with the same name. This will result in a name clash and hence the error.
Change the name of one or the other to resolve this.
So for example, this code should work for you:
class CallDict(object):
def __init__(self):
self.inverted_index = {}
def get_inverted_index_items(self):
print self.inverted_index.items()
And check it using:
>>> c = CallDict()
>>> c.get_inverted_index_items()
[]
Also check out ozgur's answer for doing this using #property decorator.
In addition to mu's answer,
#property
def invertedIndexItems(self):
print self.invertedIndex.items()
then here is how you'll cal it:
if __name__ == "__main__":
c = callDict()
print c.invertedIndexItems
Methods are attributes in Python, so you can't share the same name between them. Rename one of them.
I am learning about classes in Python, using Python 3.4.1 and am attempting to make a class and then call the methods from that class. I have looked at other questions related to this and unfortunately, I can't seem to make it work. Here is my class (copied straight from the book)
class Counter(object):
"""Models a counter"""
instances = 0
def __init__(self):
"""Sets up counter"""
Counter.instances += 1
self.reset()
def reset(self):
"""Sets counter to 0"""
self._value=0
def increment(self, amount = 1):
"""Adds amount to counter"""
self._value += amount
def decrement(self, amount = 1):
"""Subtracts amount from counter"""
self._value -= amount
def getValue(self):
return self._value
def __str__(self):
return str(self._value)
def __eq__(self, other):
"""Returns True if self == other and False if not"""
if self is other:
return True
if type(self)!=type(other):
return False
return self._value==other._value
and this is how I'm calling it from another file (in the same folder):
import Counter
h = Counter()
print(h.getValue())
and this is the error I'm getting:
Traceback (most recent call last):
File "C:/Python34/learning/classtest.py", line 3, in <module>
h = Counter()
TypeError: 'module' object is not callable
I can type import Counter just fine into the shell, but when I get to h = Counter() I get the same error. I know I'm doing something wrong, but what?
You named your module Counter too; the class is contained in the module:
import Counter
h = Counter.Counter()
Alternatively, import the class from the module:
from Counter import Counter
h = Counter()
This is why the Python style guide recommends you use all lower-case names for your modules. In Python, the module name does not have to match the class contained, and you are not limited to just one class in a module. A module can contain just functions or any other Python object too.
Had you named your module file counter (all lowercase) instead, it would perhaps have been more obvious that the module and contained class are two distinct concepts. :-)
In simple terms, the line:
import Counter
only makes the module Counter available for use. If you want to use one of the tools that it contains, such as the class Counter, you need to qualify it with the module name:
import Counter
h = Counter.Counter()
Or, you can import the tools you want directly:
from Counter import Counter
h = Counter()
Here is a reference on importing in Python.
Also, PEP 8, the official style guide for Python code, states that module names should be lowercase:
Modules should have short, all-lowercase names. Underscores can be
used in the module name if it improves readability. Python packages
should also have short, all-lowercase names, although the use of
underscores is discouraged.
Therefore, it would be best if you renamed the Counter module to counter.
You want Counter.Counter instead, because your file is named Counter.py as well.
If you don't call h = Counter.Counter(), you are basically trying to invoke the module as a function:
>>> import math
>>> math()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
You have two options.
1. Call import Counter and then call h = Counter.Counter()
import Counter
h = Counter.Counter()
print(h.getValue())
2. Call from Counter import Counter and then call h = Counter()
from Counter import Counter
h = Counter()
print(h.getValue())
Sorry if I did not explain myself clearly.
I would like to create a wrapper to call pre-defined functions with different number of inputs. Of course, I can create an individual wrapper for each function, but I am wondering if there is a way to create a generic wrapper for all cases.
The functions that should be called are named 'fun1' and 'fun2' with different number of inputs. I need to create a wrapper 'fun_wrap(func_name, uncertain amount of inputs)', which only needs the function name to be called and its associated amount of inputs.
One more thing, I need to change the input names by adding '_in' and make them global variables first. Below is my broken code. Thanks for any suggestions!
def fun1(a,b):
return a+b
def fun2(a,b,c):
return a*b/c
def set_globals(**kwargs):
for argname in kwargs:
globals()['%s_in' % argname] = kwargs[argname]
def fun_wrap(func_name, uncertain amount of inputs):
ffunc_name(set_globals(uncertain amount of inputs))
In this way, if I can call final_fun with arguments like:
fun_wrap(fun1,a,b)
fun_wrap(fun2,a,b)
UPDATE
I tried to use *arg, but failed...
def fun1(a,b):
return a+b
def fun2(a,b,c):
return a*b/c
def set_globals(**kwargs):
for argname in kwargs:
globals()['%s_in' % argname] = kwargs[argname]
def fun_wrap(func_name, *arg):
func_name(set_globals(*arg))
fun_wrap(fun2,a=1,b=2,c=3)
got error:
Traceback (most recent call last):
File "D:\Dropbox\AppPest\rice\try.py", line 19, in <module>
fun_wrap(fun2,a=1,b=2,c=3)
TypeError: fun_wrap() got an unexpected keyword argument 'a'
def fun1(a,b):
return a + b
def fun2(a,b,c):
return a * b / c
def set_globals(**kwargs):
for argname in kwargs:
globals()['%s_in' % argname] = kwargs[argname]
def fun_wrap(func, **kwargs):
set_globals(**kwargs) # made the call to set_globals before calling your function
return func(**kwargs) # return the value returned by the functions called