Create a fake class that also cheats is instance

Preface

Nowadays, the word delegation is more common than inheritance, so it's common to create a class that wraps an object for delegation.

In such a case, the part that branches at is instance becomes troublesome. (For this, code that uses a branch that does not do duck typing in the first place is good. There is also a story that there is no)

Is it possible to cheat the branch of isinstance?

Define a property called class.

How can I cheat the branch of is instance? Surprisingly easy and the property __class__ If you define, you will go to see it when evaluating with is instance.

Code for confirmation

Let's try the behavior below. About the case where the User object is wrapped with a Wrapper object called LoggedWrapper. I'm checking if I'm cheating on the branch of is instance.

# -*- coding:utf-8 -*-
import logging
logger = logging.getLogger(__name__)


class LoggedWrapper(object):
    def __init__(self, ob):
        self.ob = ob

    def __getattr__(self, k):
        logger.debug("action:%s", k)
        return getattr(self.ob, k)

    @property
    def __class__(self):
        return self.ob.__class__


from collections import namedtuple
User = namedtuple("User", "name age")

user = User("foo", 20)
wrapped = LoggedWrapper(user)

logging.basicConfig(level=logging.NOTSET)
print(wrapped.name)
print(wrapped.age)

# DEBUG:__main__:action:name
# foo
# DEBUG:__main__:action:age
# 20

print(isinstance(wrapped, User))
# True

By the way, since __class__ exists in the Wrapper object, log is not output.

Recommended Posts

Create a fake class that also cheats is instance
Python: Create a class that supports unpacked assignment
Create a life game that is manually updated with tkinter
Create an instance of a predefined class from a string in Python
[Note] Significance that __unicode__ is necessary when defining a Django model class
Create a Python function decorator with Class
Build a blockchain with Python ① Create a class
A class that hits the DMM API
Create a new dict that combines dicts
[Python] Create a LineBot that runs regularly
Create a bot that boosts Twitter trends
I tried to create a class that can easily serialize Json in Python
Decorator (@pureinstansemethod) that defines a pure instance method
[Python / Tkinter] A class that creates a scrollable Frame
Create a page that loads infinitely with python
[Note] Create a one-line timezone class with python
Python: Prepare a serializer for the class instance: