简体   繁体   中英

How to force a python object to be of some specific other type for isinstance?

Assume

class A(object):
    def init(self):
        pass

and

o = object()

I want to force o to be of type A such that

isinstance(o, A) == True

is truthy.

Can this be done?

Note i am interested in both 2.7 and 3+ solutions.

You need to change the class of your object. This is not usually recommendend, as the documentation points out:

It is possible in some cases to change an object's type, under certain controlled conditions. It generally isn't a good idea though, since it can lead to some very strange behaviour if it is handled incorrectly

If you had to "upcast" objects (upcast doesn't exist in Python) using two classes that you created

class A:
    pass

class B(A):
    pass

it would be easy to do what you're asking for:

a = A()
isinstance(a, B) # False
a.__class__ = B
isinstance(a, B) # True

However, this can't work with objects of type object . The documentation clearly says that

object does not have a __dict__ , so you can't assign arbitrary attributes to an instance of the object class.

where __dict__ is a dictionary or other mapping object used to store an object's writable attributes.

Indeed:

o = object()
o.__class__ = A
# __class__ assignment only supported for heap types or ModuleType subclasses

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM