Category Archives: Python

Python: __ new__ Method and the processing of typeerror: object() takes no parameters

Some Python books or blogs use the__ init__ Methods are called constructors, which is not strict because the method that creates the instance is__ new__, The method of instance initialization is__ init__, __ new__ Method returns an instance, and__ init__ Return to none

In understanding__ init__ And__ new__ I found an article: explain the differences in Python__ init__ And__ new__, There is this Code:

# -*- coding: utf-8 -*-
class Person(object):
    """Silly Person"""
 
    def __new__(cls, name, age):
        print ('__new__ called.')
        return super().__new__(cls, name, age)  # >>>>wrong<<<<
 
    def __init__(self, name, age):
        print ('__init__ called.')
        self.name = name
        self.age = age
 
    def __str__(self):
        return '<Person: %s(%s)>' % (self.name, self.age)
 
if __name__ == '__main__':
    piglei = Person('piglei', 24)
    print (piglei)

Error: typeerror: object() takes no parameters

Obviously, the base class object does not accept parameters, so you need to change the line in question to:

return super().__ new__( cls)

In fact, the above example is unnecessary__ new__ Method, just to show the order of method calls__ new__ Method is used when inheriting some immutable classes (such as int, STR, tuple). For example, to create a float type that always retains two decimal places, you can write as follows:

# -*- coding: utf-8 -*-
class RoundFloat(float):
    def __new__(cls, value):
        return super().__new__(cls, round(value, 2))   
 
print(RoundFloat(3.14159))  #3.14

How to Solve Python TypeError: object of type ‘int‘ has no len()

Error: object of type ‘int’ has no len()

solution problems

Error: object of type ‘int’ has no len()

solution path

Type Error: No target type of int ()

Solution methods

Very simple errors, but roughly resulted!
replace
plt.xticks(3, [‘111’, ‘222’, ‘333’]
with
plt.xticks([1,2,3), [‘111’, ‘222’, ‘333’]

 

Python TypeError: Object of type int64 is not JSON serializable

Questions

In the process of using JSON. Dumps (param) to convert Python objects to JSON, the following problems appear: typeerror: object of type Int64 is not JSON serializable type

The code is as follows:

param = {
        'remoteId': 'remoteId',
        'fieldCode': 'fieldCode',
        'paramName': 'paramName',
        'operation': 'operation',
        'operationName': 'operationName',
        'paramValue': 0
    }
...
json.dumps(param)

Why

0 in 'paramvalue ': 0 is converted into Int64 object by pandas, which is not recognized by JSON library

Solution

Change the Int64 object into a normal string type. As follows:

'paramValue': str(0)

or

df['paramValue'].apply(str)

[Solved] Python Error: datetime.datetime is not JSON serializable

Question:

The project is developed with Django, and the returned data contains a time field. When JSON. Dumps(), it will prompt: datetime. Datetime is not JSON serializable

Solution:

import json  
from datetime import date, datetime
  
class DateEncoder(json.JSONEncoder):  
    def default(self, obj):  
        if isinstance(obj, datetime):  
            return obj.strftime('%Y-%m-%d %H:%M:%S')  
        elif isinstance(obj, date):  
            return obj.strftime("%Y-%m-%d")  
        else:  
            return json.JSONEncoder.default(self, obj)

When using it, return will do

return HttpResponse(json.dumps(rows, cls=DateEncoder))

Python TypeError: ‘numpy.float64’ object cannot be interpreted as an index

When training stage1 RPN, there is a prompt error of ‘numpy. Float64’ object cannot be interpreted asanindex. Almost all blogs point out that the version of numpy needs to be changed. After doing so, there is an importerror: numpy. Core. Multiarray failed to import. This problem is caused by the mismatch of numpy, which forms a vicious circle, We can consider solving ‘numpy. Float64’ object cannot be interpreted as an index from the root

TypeError: 'numpy.float64' object cannot be interpreted as an index

1) /home/xxx/py-faster-rcnn/lib/roi_data_layer/minibatch.py

Line 26: fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image)
to fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image).astype(np.int)
Line 174 & 175 to

for ind in inds:
cls = clss[ind]
start =int( 4 * cls)
end = int(start + 4)
bbox_targets[ind, start:end] = bbox_target_data[ind, 1:]
bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS

2) /home/xxx/py-faster-rcnn/lib/datasets/ds_utils.py

Line 12: hashes = np.round(boxes * scale).dot(v)
to hashes = np.round(boxes * scale).dot(v).astype(np.int)

3) /home/xxx/py-faster-rcnn/lib/fast_rcnn/test.py

Line 129: hashes = np.round(blobs['rois'] * cfg.DEDUP_BOXES).dot(v)
to hashes = np.round(blobs['rois'] * cfg.DEDUP_BOXES).dot(v).astype(np.int)

4) /home/xxx/py-faster-rcnn/lib/rpn/proposal_target_layer.py

Line 60: fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image)
to fg_rois_per_image = np.round(cfg.TRAIN.FG_FRACTION * rois_per_image).astype(np.int)

After solving the previous problem, there is a typeerror: slice indexes must be integers or none or have an__ index__ If the version of numpy is not changed,
Modify/home/xxx/py fast RCNN/lib/RPN/proposal_ target_ Layer.py, go to line 123:

for ind in inds:
        cls = clss[ind]
        start = 4 * cls
        end = start + 4
        bbox_targets[ind, start:end] = bbox_target_data[ind, 1:]
        bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS
    return bbox_targets, bbox_inside_weights

Here, ind, start and end are all numpy.int types, and data of this type cannot be used as indexes, so it is necessary to cast them. The conversion results are as follows:

for ind in inds:
        ind = int(ind)
        cls = clss[ind]
        start = int(4 * cos)
        end = int(start + 4)
        bbox_targets[ind, start:end] = bbox_target_data[ind, 1:]
        bbox_inside_weights[ind, start:end] = cfg.TRAIN.BBOX_INSIDE_WEIGHTS
    return bbox_targets, bbox_inside_weight

Python3 urlopen() TypeError: can’t convert ‘bytes’ object to str im…

recently wrote the program using urllib. Request urlopen to read pages of text files, the results appeared a TypeError, problems and solving methods will now be recorded as follows, hope to help those encountered similar problems:

uses the Python version 3.5.2

 1 # -*- coding: UTF-8 -*-
 2 #!/usr/bin/python
 3 # Filename: urllib.py
 4 import random
 5 from urllib.request import urlopen
 6 import sys
 7 
 8 WORD_URL = "http://learncodethehardway.org/words.txt"
 9 WORDS = []
10 
11 PHRASES = {
12         " class %%%(%%%):":
13             "Make a class named %%% that is-a %%%.",
14         "class %%%(object):\n\tdef__init__(self,***)":
15             "class %%% has-a __init__ that takes self and *** parameters.",
16         "*** = %%%()":
17             "Set *** to an instance of class %%%.",
18         "***.***(@@@)":
19             "From *** get the *** function, and call it with parameters self,@@@.",
20         "***.*** = '***'":
21             "From *** get the *** attribute and set it to '***'."
22             }
23             
24 PHRASES_FIRST = False
25 if len(sys.argv) == 2 and sys.argv[1] == "english":
26     PHRASES_FIRST = True
27                 
28 for word in urlopen(WORD_URL).readlines():
29     WORDS.append(word.strip())
30                 
31 def convert(snippet, phrase):
32     class_names = [w.capitalize() for w in
33                 random.sample(WORDS, snippet.count("%%%"))]
34     other_names = random.sample(WORDS, snippet.count("***"))
35     results = []
36     param_names = []
37                 
38     for i in range(0, snippet.count("@@@")):
39         param_count = random.randint(1,3)
40         param_names.append(', '.join(random.sample(WORDS, param_count)))
41         #param_names.append(', '.join('%s' %id for id in random.sample(WORDS, param_count)))
42                     
43     for sentence in snippet, phrase:
44         result = sentence[:]
45         print(result)
46                     
47         for word in class_names:
48             result = result.replace("%%%", word, 1)
49 
50         for word in other_names:
51             result = result.replace("***",word, 1)
52                     
53         for word in param_names:
54             result = result.replace("@@@", word, 1)
55                         
56         results.append(result)
57                 
58     return results
59         
60 try:
61     while True:
62         snippets = list(PHRASES.keys())
63         random.shuffle(snippets)
64         
65         for snippet in snippets:
66             phrase = PHRASES[snippet]
67             question, answer  = convert(snippet, phrase)
68             if PHRASES_FIRST:
69                 question, answer = answer,question
70                 
71             print (question)
72             
73             input ("> ")
74             print ("ANSWER: %s\n\n" % answer)
75 except EOFError:
76     print ("\nBye!")

= TypeError: Can’t convert ‘bytes’ object to STR IMPLICITLY

after the access to information found that urlopen () returns a bytes object, if you need to string operations, he need to explicitly convert it into a string, can appear otherwise the above problems.

we when reading web content directly convert them to encoding to utf-8, can continue to use. Change line 29 of the above code to

WORDS.append(word.strip().decode('utf-8'))

problem solved.

Python Exception: TypeError: write() argument must be str, not list

When writing to a file, an error is reported: TypeError: write() argument must be str, not list

Reason: The content written by python should be of string type

Code.

fp = open(“a.txt”,”w”)
fp.write([1,2,3])
fp.close()

>>> fp = open("a.txt","w")
>>> fp.write([1,2,3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: write() argument must be str, not list
>>> fp.close()

If the writing content is string type, OK

fp = open("a.txt","w")
fp.write('[1,2,3]')#Processing file contents to string type
fp.close()

How to Solve Python TypeError: ‘module’ object is not callable

When I am used to writing java code, I will try to define package when I write Python code. However, when I introduce it, I report an error: typeerror: ‘module’ object is not called

Why

For example, I create the person. Py source file in the package, and then create the student class in this file

How to import the student class

Habitual thinking, from clazz. Student is OK, but it is not

The correct way is from clazz.person import student or from clazz.person import*

That is to say, which classes are imported from which py file under which package

PaddlePaddle Error: ‘map’ object is not subscriptable

Problem Description: I wrote the machine translation model according to the official document of paddlepaddle, and this error occurred. I compared the code in the document, and there was no error

error message:

Original sentence:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-27-e241afef7936> in <module>()
     20 
     21     print("Original sentence:")
---> 22     print(" ".join([src_dict[w] for w in feed_data[0][0][1:-1]]))
     23 
     24     print("Translated score and sentence:")

TypeError: 'map' object is not subscriptable

Problem recurrence:

exe = Executor(place)
exe.run(framework.default_startup_program())

for data in test_data():
    feed_data = map(lambda x: [x[0]], data)
    feed_dict = feeder.feed(feed_data)
    feed_dict['init_ids'] = init_ids
    feed_dict['init_scores'] = init_scores

    results = exe.run(
        framework.default_main_program(),
        feed=feed_dict,
        fetch_list=[translation_ids, translation_scores],
        return_numpy=False)

problem analysis:
in Python 3, map will return an iterative object of map type, which is different from the object directly obtained by subscript. In Python 2, there is no problem. In case of this problem, you only need to modify the code to a python 3 compatible mode

problem solving:

If you want to get the map object by subscript, you can first turn the map object into a list object, so you can get it directly by subscript

exe = Executor(place)
exe.run(framework.default_startup_program())

for data in test_data():
    feed_data = list(map(lambda x: [x[0]], data))
    feed_dict = feeder.feed(feed_data)
    feed_dict['init_ids'] = init_ids
    feed_dict['init_scores'] = init_scores

    results = exe.run(
        framework.default_main_program(),
        feed=feed_dict,
        fetch_list=[translation_ids, translation_scores],
        return_numpy=False)

Problem development:
the map() method is a built-in method in Python. The map() method in python2 is different from that in python3. In view of the necessity of everything, it will consume memory to return all the data, so it will be modified to the form of generated object, that is, it will be obtained when it is retrieved, and it will only take effect once

How to Solve Python TypeError: ‘list’ object is not callable

What will happen if the list variable and the list function have the same name?We can refer to the following code:

list = ['Puff', 'Sourdough', 'Fish', 'Camel']

tup_1 = (1, 2, 3, 4, 5)
tupToList = list(tup_1)

print(tupToList)

An error occurred after the code was run. The reason for the error is typeerror: ‘list’ object is not called

Traceback (most recent call last):
  File "D:/python_workshop/python6/lesson3_list.py", line 6, in <module>
    tupToList = list(tup_1)
TypeError: 'list' object is not callable

Callable () is a built-in function of python, which is used to check whether an object can be called. Callable refers to whether an object can be called with () brackets

In the above code, because the variable list and function list have the same name, when the function uses the list function, it finds that the list is a well-defined list, and the list cannot be called, so it throws a type error

Solution: we just need to modify the variable name list

list_1 = ['Puff', 'Sourdough', 'Fish', 'Camel']

tup_1 = (1, 2, 3, 4, 5)
tupToList = list(tup_1)

print(tupToList)

After operation and the results are normal

[1, 2, 3, 4, 5]

Therefore, when naming variables, you should avoid conflicts with Python function names and keywords