How could Reflection not lead to code smells?

后端 未结 18 2120
失恋的感觉
失恋的感觉 2020-12-12 15:02

I come from low level languages - C++ is the highest level I program in.

Recently I came across Reflection, and I just cannot fathom how it could be used without cod

18条回答
  •  心在旅途
    2020-12-12 15:14

    Very simple example in Python. Suppose you have a class that have 3 methods:

    class SomeClass(object):
        def methodA(self):
           # some code
        def methodB(self):
           # some code
        def methodC(self):
           # some code
    

    Now, in some other class you want to decorate those methods with some additional behaviour (i.e. you want that class to mimic SomeClass, but with an additional functionality). This is as simple as:

    class SomeOtherClass(object):
        def __getattr__(self, attr_name):
            # do something nice and then call method that caller requested
            getattr(self.someclass_instance, attr_name)()
    

提交回复
热议问题