Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Question

Convert inline code to code block
Source Link
Chris
  • 139.1k
  • 139
  • 317
  • 293

I know that we have to use setattr method when we are outside of an object. However, I have troubles calling setattr with unicode key leading me to use __setattr__ directly.

class MyObject(object): def __init__(self): self.__dict__["properties"] = dict() def __setattr__(self, k, v): self.properties[k] = v obj = MyObject()

class MyObject(object):
 def __init__(self):
 self.__dict__["properties"] = dict()
 def __setattr__(self, k, v):
 self.properties[k] = v
obj = MyObject()

And I get the following content of obj.properties:

  • setattr(obj, u"é", u"à"): raise UnicodeEncodeError
  • setattr(obj, "é", u"à"): {'\xc3\xa9': u'\xe0'}
  • obj.__setattr__(u"é", u"à"): {u'\xe9': u'\xe0'}

I don't understand why Python is behaving with these differences

I know that we have to use setattr method when we are outside of an object. However, I have troubles calling setattr with unicode key leading me to use __setattr__ directly.

class MyObject(object): def __init__(self): self.__dict__["properties"] = dict() def __setattr__(self, k, v): self.properties[k] = v obj = MyObject()

And I get the following content of obj.properties:

  • setattr(obj, u"é", u"à"): raise UnicodeEncodeError
  • setattr(obj, "é", u"à"): {'\xc3\xa9': u'\xe0'}
  • obj.__setattr__(u"é", u"à"): {u'\xe9': u'\xe0'}

I don't understand why Python is behaving with these differences

I know that we have to use setattr method when we are outside of an object. However, I have troubles calling setattr with unicode key leading me to use __setattr__ directly.

class MyObject(object):
 def __init__(self):
 self.__dict__["properties"] = dict()
 def __setattr__(self, k, v):
 self.properties[k] = v
obj = MyObject()

And I get the following content of obj.properties:

  • setattr(obj, u"é", u"à"): raise UnicodeEncodeError
  • setattr(obj, "é", u"à"): {'\xc3\xa9': u'\xe0'}
  • obj.__setattr__(u"é", u"à"): {u'\xe9': u'\xe0'}

I don't understand why Python is behaving with these differences

Source Link

Python setattr vs __setattr__ UnicodeEncodeError

I know that we have to use setattr method when we are outside of an object. However, I have troubles calling setattr with unicode key leading me to use __setattr__ directly.

class MyObject(object): def __init__(self): self.__dict__["properties"] = dict() def __setattr__(self, k, v): self.properties[k] = v obj = MyObject()

And I get the following content of obj.properties:

  • setattr(obj, u"é", u"à"): raise UnicodeEncodeError
  • setattr(obj, "é", u"à"): {'\xc3\xa9': u'\xe0'}
  • obj.__setattr__(u"é", u"à"): {u'\xe9': u'\xe0'}

I don't understand why Python is behaving with these differences

lang-py

AltStyle によって変換されたページ (->オリジナル) /