Python2转Python3时socket.send报错:需类字节对象而非内置函数/方法
Hey there! Your initial guess is spot-on—this error is almost always tied to Python 3's strict separation between strings (str) and byte objects (bytes), which didn't exist in Python 2. Let's break down how to fix this, and also address that weird "builtin_function_or_method" clue in the error message.
First, the core issue
In Python 2, socket.send() happily accepted regular strings because strings and bytes were interchangeable. But in Python 3, the send() method requires a bytes-like object—so passing a plain string (or worse, a function/method reference) will throw this exact error.
Step 1: Ensure self.data is actually a string (not a method/function)
Wait, the error mentions "builtin_function_or_method"—that suggests self.data might not be the string content you think it is. Double-check where you assign self.data in your code. Did you accidentally do something like this?
# Wrong: assigning the str function instead of a string value self.data = str
Instead, it should be a concrete string, like:
# Correct: assigning an actual string self.data = "Response from server"
Step 2: Convert the string to bytes before sending
Once you confirm self.data is a valid string, use the encode() method to convert it to bytes. The most common encoding is UTF-8, but you can use whatever matches your use case (like ASCII if you're only dealing with basic characters).
Update your problematic line from:
connection.send(self.data)
To:
connection.send(self.data.encode('utf-8'))
Example of the fixed code snippet
Here's how the corrected section might look in your server.py:
# Assuming self.data is properly set to a string value self.data = "Hello client!" # Convert string to bytes and send connection.send(self.data.encode('utf-8'))
Bonus: If self.data comes from a file
If you're reading self.data from a file, make sure you're either:
- Reading in text mode (default) and encoding the string, or
- Reading in binary mode (
open('file.txt', 'rb')) which gives you bytes directly (no need to encode)
That should resolve the error. Let me know if you run into any other quirks while migrating from Python 2 to 3!
内容的提问来源于stack exchange,提问作者Alex Irizarry

