Python Forum
"can't set attribute" on class - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: "can't set attribute" on class (/thread-29204.html)



"can't set attribute" on class - DreamingInsanity - Aug-22-2020

I have a class like so:
class CustomLevel(BaseLevel):

	def __init__(self, **data: dict) -> None:
		self.data = data

	@classmethod
	def fromData(cls, data: Union[dict, str]) -> CustomLevel:
		if(isinstance(data, str)):
			pass
		return cls(
			data=data.get("level_data", ""),
			name=data.get("name", "Unknown"),
			id=data.get("id", ""),
			creator=data.get("creator", "Unknown")
		)

	@property
	def data(self) -> str:
		return self.data.get("level_data", "")

	@property
	def name(self) -> str:
		return self.data.get("name", "Unknown")

	@property
	def id(self) -> str:
		return self.data.get("id", "")
		
	@property
	def creator(self) -> str:
		return self.data.get("creator", "Unknown")

	@classmethod
	def getParams(self) -> URLParameters:
		return URLParameters({
			"gameVersion": "21",
			"binaryVersion": "35",
			"gdw": "0",
			"levelID": self.id,
			"secret": "Wmfd2893gb7" #this is not a secret its the same for everyone
		})
It inherits a base class which is just a class with the exact same functions but with no code within them.
To use this class, I go:
level = CustomLevel.fromData({"id": id})
By doing this, it throws:
Error:
--- <exception caught here> --- File "/Users/everyone/.pyenv/versions/3.8.0/lib/python3.8/site-packages/twisted/internet/defer.py", line 1418, in _inlineCallbacks result = g.send(result) File "/Users/everyone/Desktop/gdreplacer/simple_server.py", line 31, in something print(self.locations[name](data)) File "/Users/everyone/Desktop/gdreplacer/level.py", line 109, in replace level = CustomLevel.fromData({"id": constants.ARGS.payload_id}) File "/Users/everyone/Desktop/gdreplacer/level.py", line 57, in fromData return cls( File "/Users/everyone/Desktop/gdreplacer/level.py", line 51, in __init__ self.data = data builtins.AttributeError: can't set attribute
It clearly doesn't like me trying to set the "data" attribute. If I print the contents of data before trying to set it, I get this:
Output:
{'data': '', 'name': 'Unknown', 'id': '88685', 'creator': 'Unknown'}
which is correct.

How come it is not letting me set an attribute?


RE: "can't set attribute" on class - Gribouillis - Aug-22-2020

The problem is that you have a read-only @property named data. The best solution is to rename the attribute. You could use _data or datadict for example.


RE: "can't set attribute" on class - DreamingInsanity - Aug-22-2020

(Aug-22-2020, 07:53 PM)Gribouillis Wrote: The problem is that you have a read-only @property named data. The best solution is to rename the attribute. You could use _data or datadict for example.
Ah that was it - thanks!