伪造对象是否是 Python 中 Class 的实例

Faking whether an object is an Instance of a Class in Python

假设我有一个 class FakePerson 模仿基础 class RealPerson 的所有属性和功能而不扩展它.在 Python 3 中,是否可以通过仅修改 FakePerson class 来伪造 isinstance() 以将 FakePerson 识别为 RealPerson 对象。例如:

class RealPerson():
    def __init__(self, age):
        self.age = age

    def are_you_real(self):
        return 'Yes, I can confirm I am a real person'

    def do_something(self):
        return 'I did something'

    # Complicated functionality here

class FakePerson(): # Purposely don't extend RealPerson
    def __init__(self, hostage):
        self.hostage = hostage

    def __getattr__(self, name):
        return getattr(self.hostage, name)

    def do_something(self):
        return 'Ill pretend I did something'

    # I don't need complicated functionality since I am only pretending to be a real person.


a = FakePerson(RealPerson(30))
print(isinstance(a, RealPerson))

假设我有一个 class 模仿了 Pandas DataFrame 行(namedtuple 对象)的大部分/所有功能。如果我有一个行列表 list_of_rows,Pandas 通过 pandas.DataFrame(list_of_rows) 生成一个 DataFrame 对象。但是,由于 list_of_rows 中的每个元素都不是 namedtuple 而只是 'fake',构造函数无法将这些 'fake' 行对象识别为真实行,即使是假对象伪造 Pandas namedtuple.

的所有底层方法和属性

isInstance() function is a python builtin who's implementation explicitly looks for an object's (direct, indirect or virtual) class or subclass. The 'imitations' you're referring to is also known as duck typing。在您的情况下,看起来您 do 想要扩展或子class DataFrame 行。虽然,您 可能 分配 class 属性,但要知道这可能会导致未定义的行为,因为它是实现 -具体。

您可能需要 class 您的 RealPerson class。

class RealPerson:
    def __init__(self, age):
        self.age = age

    def are_you_real(self):
        return 'Yes, I can confirm I am a real person'

    def do_something(self):
        return 'I did something'

    # Complicated functionality here

class FakePerson: # Purposely don't extend RealPerson
    def __init__(self, hostage):
        self.hostage = hostage

    def __getattr__(self, name):
        return getattr(self.hostage, name)

    def do_something(self):
        return 'Ill pretend I did something'

    # I don't need complicated functionality since I am only pretending to be a real person.


class BetterFakePerson(RealPerson):
    pass

BetterFakePerson.__init__ = FakePerson.__init__
BetterFakePerson.__getattr__ = FakePerson.__getattr__
BetterFakePerson.do_something = FakePerson.do_something

a = FakePerson(RealPerson(30))
print(isinstance(a, RealPerson))

b = BetterFakePerson(RealPerson(30))
print(isinstance(b, RealPerson))

希望这个答案对你来说不会太晚哈哈