When where and how can i change the __class__ attr of an object?

python update class attributes
python add attribute to class
python class attributes
python get class attributes
python class attributes list
python object attributes
python class property
python attribute decorator

I'd like to be able to do:

>>> class a(str):
...     pass
...
>>> b = a()
>>> b.__class__ = str
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __class__ assignment: only for heap types

I've solved it in this way:

>>> class C(str):
...     def __getattribute__(self, name):
...         if name == '__class__':
...             return str
...         else:
...             return super(C, self).__getattribute__(name)
...         
>>> c = C()
>>> c.__class__
<type 'str'>

python, I've solved it in this way: >>> class C(str): def __getattribute__(self, name): if name == '__class__': return str else: return super(C, self). In the above snippet, attributeis a class attribute and you can access using: NewClass.attribute. or. object = NewClass() object.attribute. They both will print “This is an attribute of a class”.

Python 2 doesn't have a unified object hierarchy (ie. not everything is descended from the object class). Anything that is part of this hierarchy can be played with via __class__, but those that aren't cannot be modified in this way (or at all, really). These are called Python's "types", and they're hard-coded in C. Examples of types are str, int, float, list, tuple, etc. This means that you cannot use types in the same ways as classes, for example you cannot change the class of an instance of a type, you cannot add, remove or modify methods of types, etc. The following transcript shows the difference in behaviour between types such as str (hard-coded, non-dynamic C constructs) and classes I've called A and B (changeable, dynamic, Python constructs):

>>> str
<type 'str'>
>>> class A:
...     pass
... 
>>> a = A()
>>> A
<class __main__.A at 0xb747f2cc>
>>> a
<__main__.A instance at 0xb747e74c>
>>> type(a)
<type 'instance'>
>>> type(A)
<type 'classobj'>
>>> type(str)
<type 'type'>
>>> type(type(a))
<type 'type'>
>>> type(type(A))
<type 'type'>
>>> A.foo = lambda self,x: x
>>> a.foo(10)
10
>>> A().foo(5)
5
>>> str.foo = lambda self,x: x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'str'
>>> 'abc'.foo(5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'foo'
>>> class B:
...     pass
... 
>>> a.__class__
<class __main__.A at 0xb747f2cc>
>>> a.__class__ = B
>>> a
<__main__.B instance at 0xb747e74c>
>>> 'abc'.__class__
<type 'str'>
>>> 'abc'.__class__ = B
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __class__ must be set to new-style class, not 'classobj' object
>>> class B(object):
...     pass
... 
>>> 'abc'.__class__ = B
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __class__ assignment: only for heap types

Python Power!: The Comprehensive Guide, dir(MyClass) ['__doc ', '__module__', 'name'] Notice that the name attribute is both the class definition and the variable definition, but that the name attribute is The dictionary object, by the way, is a writeable entity, so you can change the  We can see in the following interactive Python session that the class attribute "a" is the same for all instances, in our example "x" and "y". Besides this, we see that we can access a class attribute via an instance or via the class name:

Only classes that were defined with a class keyword could be used for __class__ attribute assignment:

>>> class C:
    pass

>>> class D:
    pass

>>> C().__class__ = D
>>>

Learning Python: Powerful Object-Oriented Programming, Powerful Object-Oriented Programming Mark Lutz decide to extend ListInstance's __str__ to also print all the class attributes that an instance inherits, you're safe; because it's an inherited method, changing __str__ automatically updates the  I have a class that is provided to me by an external library. I have created a subclass of this class. I also have an instance of the original class. I now want to turn this instance into an insta

I tried this way!

>>> class C(str):
...     __class__ = str
...
>>> c = C()
>>> c.__class__
<class 'str'>

Python Tutorial: Class vs. Instance Attributes, Object-oriented programming in Python: instance attributes vs. class We define class attributes outside of all the methods, usually they are placed at the top, __​dict__ {} >>> A.__dict__ dict_proxy({'a': "This is changing the class attribute 'a'! So, we’ve now seen that every Python object has attributes, that we can retrieve existing attributes using dot notation or “getattr”, and that we can always set attribute values. If the attribute didn’t exist before our assignment, then it certainly exists afterwards. We can assign new attributes to nearly any object in Python. For example:

Making Use of Python, Any changes made to the attributes of a class are reflected in the __dict__ attribute of only that class. dir() and __dict__ do not display all the built-in functions and variables of a class. Another way to class object before you can call a method. The code that you posted there is a no-op; self.__class__ == c1 is not part of a conditional so the boolean is evaluated but nothing is done with the result. You could try to make an abstract base class that checks to see if self.__class__ is equal to the abstract class as opposed to a hypothetical child (via an if statement), in order to prevent the instantiation of the abstract base class

Pro Python, Unlike __get__(), this operation can only be performed on instance objects. This is intentional, because without it, there would be no way to modify or remove a The class can still be determined by accessing the __class__ attribute on the​  If you refuse to change __class__, then you might have to include a stage attribute, and use a lot of if statements, or reassign a lot of attributes pointing to different stage's functions Yes, I've used a stage attribute, but that's not a downside—it's the obvious visible way to keep track of what the current stage is, better for debugging and for readability.

Python Class Attributes: Examples of Variables, Python class attributes can lead to elegant code, as well as frustrating bugs. In this class Service(object): def __init__(self, other_data): self.data Edit: as Pedro Werneck kindly pointed out, this behavior is largely intended to help out with  Most people know just one thing when it comes to attribute access - the dot '.' (as in x.some_attribute). In simple terms, attribute access is the way you retrieve an object linked to the one you already have.

Comments
  • closely related: stackoverflow.com/questions/990758/…
  • I'd like to say that this is a fairly bad message from the interpreter, since the term "heap type" isn't familiar to most Python programmers and there doesn't appear to be any way in Python 3 to create a class whose instances have an assignable class. Or at least I haven't found one.
  • @holdenweb bugs.python.org/issue4600
  • Nice one. I meant, of course, an assignable __class__ attribute.
  • Everything in python 2 is a object instance.
  • You mean that not all classes are instances of type.
  • That´s not what they say here:bytes.com/topic/python/answers/449635-assigning-self-class
  • In fact, I think __mro__ is the only read-only attribute there.
  • I think this is not total true. You may have class A(str) and you cant assign A.
  • See mail-archive.com/python-list@python.org/msg52950.html for a list of differences between types that might give troubles.