i've copied a python code from a guide:
class Carta:
ListaSemi=["Fiori","Quadri","Cuori","Picche"]
ListaRanghi=["impossibile","Asso","2","3","4","5","6",\
"7","8","9","10","Jack","Regina","Re"]
def __init__(self, Seme=0, Rango=0):
self.Seme=Seme
self.Rango=Rango
def __str__(self):
return (self.ListaRanghi[self.Rango] + " di " + self.ListaSemi[self.Seme])
def __cmp__(self, Altro):
#controlla il seme
if self.Seme > Altro.Seme: return 1
if self.Seme < Altro.Seme: return -1
#se i semi sono uguali controlla il rango
if self.Rango > Altro.Rango: return 1
if self.Rango < Altro.Rango: return -1
return 0
when i call from shell:
>>> Carta1=Carta(1,11)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
I'm using python version 2.7.
what's wrong??
thanks
I assume that the snippet above is saved as Carta.py and that you ran in your interactive shell:
>>> import Carta
>>> Carta1=Carta(1,11)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
This way, you try to call/instantiate the module instead of the class inside it. You have basically two options to fix this, changing either the import or the constructor call:
>>> from Carta import Carta
>>> Carta1=Carta(1,11)
>>> import Carta
>>> Carta1=Carta.Carta(1,11)
If you rename either the module file or the class so that you can distinguish them better, it becomes clear.
Related
When I am iterating through my variable it gives me an error which I show as below.
Traceback (most recent call last):
File "C:\Users\ZHEN YUAN\Desktop\东航第一步\wen2.py", line 13, in <module>
for i in Names:
TypeError: 'NoneType' object is not iterable
Your function wenjian() does not have any return statements, so it will always return None, by default. That's why Names = wenjian(file) assigns the value None to Names, and so you can't iterate over Names with the for loop.
import os
def wenjian(file):
for root,dirs,files in os.walk(file):
for file in files:
filename = os.path.join(root,file)
print (filename[-28:])
file = ("C:\Users\ZHEN YUAN\Desktop\东航try")
Names = wenjian(file)
for i in Names:
print (i[1])
PS C:\Users\ZHEN YUAN> & python "c:/Users/ZHEN YUAN/Desktop/东航第一步/wen2.py"
\Desktop\东航try\C2002455.xlsx
Traceback (most recent call last):
File "c:/Users/ZHEN YUAN/Desktop/东航第一步/wen2.py", line 14, in <module>
for i in Names:
TypeError: 'function' object is not iterable
I'm trying to call a class method inside the init function of the class. I pass in a string to the function but the error shows that its a none type object.
class UserSettings(object):
"""Value object representing a user's settings."""
def __init__(
self, user_id, email, username=None):
self.user_id = user_id
self.email = email
self.profile_picture_data_url = self.fetch_gravatar(email)
#classmethod
def fetch_gravatar(cls, email):
base_url = "http://www.gravatar.com/avatar/"
avatar_url = base_url + hashlib.md5(email.lower()).hexdigest() + "?"
avatar_url += urllib.urlencode({'d':'retro', 's':str(AVATAR_SIZE)})
return avatar_url
Here's the error:
Traceback (most recent call last):
File "/home/travis/build/oppia/oppia/core/domain/user_services_test.py", line 78, in test_invalid_emails
user_services.get_or_create_user('user_id', email)
File "/home/travis/build/oppia/oppia/core/domain/user_services.py", line 297, in get_or_create_user
user_settings = _create_user(user_id, email)
File "/home/travis/build/oppia/oppia/core/domain/user_services.py", line 284, in _create_user
preferred_language_codes=[feconf.DEFAULT_LANGUAGE_CODE])
File "/home/travis/build/oppia/oppia/core/domain/user_services.py", line 55, in __init__
self.profile_picture_data_url = self.fetch_gravatar(email)
File "/home/travis/build/oppia/oppia/core/domain/user_services.py", line 129, in fetch_gravatar
avatar_url = base_url + hashlib.md5(email.lower()).hexdigest() + "?"
AttributeError: 'NoneType' object has no attribute 'lower'
AttributeError: 'NoneType' object has no attribute 'lower'
This tells you that you are attempting to read an attribute named lower on the singleton object None.
Now, you use lower in a method call on email. Therefore, email is None.
You must be calling the method with the value None, or an argument that evaluates to None.
# calling the class method:
>>> UserSettings.fetch_gravatar('a#example.com')
'http://www.gravatar.com/avatar/b418773a2c51fb9777a1648346fa7394?s=16&d=retro'
# create instance, call method:
>>> user_settings = UserSettings(user_id=1, email='jill#example.com')
>>> user_settings.fetch_gravatar('jill#example.com')
'http://www.gravatar.com/avatar/e84a7df193a44f643668b74a2bbfdde6?s=16&d=retro'
# calling with a No arguments gives TypeError
>>> UserSettings.fetch_gravatar()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: fetch_gravatar() takes exactly 2 arguments (1 given)
# calling with None gives your error:
>>> UserSettings.fetch_gravatar(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 11, in fetch_gravatar
AttributeError: 'NoneType' object has no attribute 'lower'
I got an error while run python proxy.py
$ python proxy.py
INFO - [Sep 28 14:59:19] getting appids from goagent plus common appid pool!
Traceback (most recent call last):
File "proxy.py", line 2210, in <module>
main()
File "proxy.py", line 2180, in main
pre_start()
File "proxy.py", line 2157, in pre_start
common.set_appids(get_appids())
File "proxy.py", line 94, in get_appids
fly = bytes.maketrans(
AttributeError: type object 'str' has no attribute 'maketrans'
The proxy.py file in https://code.google.com/p/smartladder/,
def get_appids():
fly = bytes.maketrans(
b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
b"nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM"
)
f = urllib.request.urlopen(url="http://lovejiani.com/v").read().translate(fly)
d = base64.b64decode(f)
e = str(d, encoding='ascii').split('\r\n')
random.shuffle(e)
return e
You are running code written for Python 3, with Python 2. This won't work.
maketrans is a classmethod on the bytes built-in type, but only in Python 3.
# Python 3
>>> bytes
<class 'bytes'>
>>> bytes.maketrans
<built-in method maketrans of type object at 0x10aa6fe70>
In Python 2, bytes is an alias for str, but that type does not have that method:
# Python 2.7
>>> bytes
<type 'str'>
>>> bytes.maketrans
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'str' has no attribute 'maketrans'
Run your code with Python 3 instead, or translate all code in this project to Python 2; the latter requires in-depth knowledge of how Python 2 and 3 differ and is likely a major undertaking.
Just the illustrated function, translated to Python 2, would be:
import string
import urllib2
import base64
import random
def get_appids():
fly = string.maketrans(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
"nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM"
)
f = urllib2.urlopen("http://lovejiani.com/v").read().translate(fly)
d = base64.b64decode(f)
e = unicode(d, encoding='ascii').split(u'\r\n')
random.shuffle(e)
return e
I wish to do some kind of reflection thing where given a line number and a module, I get back the name of the function in that module containing that line. Is this possible in Python?
There is no built-in way to do this in python. However, you could define a function to do something like that, but it would handle modules as files in your current directory:
import re
def get_function_name(module, line):
module_file = module.replace('.', '/') + '.py'
lines = open(module_file, 'r').xreadlines()
i = line - 1
try:
while i:
tmp = next(lines)
i -= 1
except StopIteration:
raise EOFError('Not enought lines in module %s' % module)
function_line = next(lines)
function_name = re.match('def (\w+)\([^)]*\):', function_line)
if function_name:
return function_name.group(1)
raise ValueError('No function declared on line %s' % line)
This function is opening the module passed as a file, iterating until reached the passed line, and then, searching the name of the function using regular expressions. If there was no function declared on the passed line or the line passed exceeded the number of lines of the file, it will raise an Error. E.g.:
>>> get_function_name('my_module.my_submodule', 24)
'my_function_name'
>>> get_function_name('my_module.my_submodule', 25)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 15, in get_function_name
ValueError: No function declared on line 17
>>> get_function_name('my_module.my_submodule', 123456)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 10, in get_function_name
EOFError: Not enought lines in module
Hello I have an Error and I don´t the reason:
>>> class Fruits:pass
...
>>> banana = Fruits()
>>> banana.color = 'yellow'
>>> banana.value = 30
>>> import pickle
>>> filehandler = open("Fruits.obj",'w')
>>> pickle.dump(banana,filehandler)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python31\lib\pickle.py", line 1354, in dump
Pickler(file, protocol, fix_imports=fix_imports).dump(obj)
TypeError: must be str, not bytes
>>>
I don´t know how to solve this error because I don´t understand it.
Thank you so much.
You have to open your filehandler in binary mode, use wb instead of w:
filehandler = open(b"fruits.obj","wb")