0

base class:

class BaseTest():
    m_list = ['a', 'b']

I want to let every instance of BaseTest and modify its member variable by decorator, because I don't want to change code of BaseTest,as

m_list = ['a', 'b', 'c']

Then next time:

test = BaseTest()
print test.m_list
#Output: ['a', 'b', 'c']

How can I implement?

Wilence
  • 343
  • 2
  • 3
  • 8
  • You want to modify it at class level or instance level? – Ashwini Chaudhary Nov 27 '15 at 06:51
  • class level may be better. – Wilence Nov 27 '15 at 06:54
  • `m_list` is not an instance member, but a class member, thus there is no 'its' for instances with regard to it. – decltype_auto Nov 27 '15 at 06:54
  • Of course m_list is class member, but every instance can access it. What I want is m_list in every instance print as ```['a', 'b', 'c']``` – Wilence Nov 27 '15 at 07:02
  • 3
    Your words aren't put together in a meaningful way. It's impossible to tell what you're asking. As a wild guess, does [this](http://stackoverflow.com/questions/1680528/how-do-i-avoid-having-python-class-data-shared-among-instances) answer your question? – user2357112 Nov 27 '15 at 07:08
  • 1
    If you want every instance to have `m_list` as `['a', 'b', 'c']`, why don't you just set that as the value in the class? – BrenBarn Nov 27 '15 at 07:12
  • It is not a nice way to change code of BaseTest() for some reason. I want to write a monkey patch using decorator. – Wilence Nov 27 '15 at 07:16
  • Maybe [this question](http://stackoverflow.com/questions/681953/python-class-decorator) helps you: There is an [answer using a metaclass](http://stackoverflow.com/a/682052/923794) and an [answer using a class decorator](http://stackoverflow.com/a/682242/923794). Of course, inheritance is recommended everywhere, so I don't even repeat that here. MonkeyPatching is often best done with inheritance in Python. – cfi Nov 27 '15 at 07:35

2 Answers2

2
def dec(cls):
    cls.m_list = ['a', 'b', 'c']
    return cls

@dec
class BaseTest():
    m_list = ['a', 'b']
Alex Polekha
  • 1,590
  • 15
  • 13
0
# here you have a class
class BaseTest():
    m_list = ['a', 'b']
    quantity=12345

# here you extending from existing class
class BaseTestextended(BaseTest):
    m_list = ['a', 'b','c']

bte= BaseTestExtended()
bte.mlist # outputs ['a','b','c']
bte.quantity # outputs 12345

if you want object return modified params by function, you can do like this:

class BaseTestextended(BaseTest):
    @classmethod
    def mlist(self):
        return m_list.append('c')
Dmitry Yudin
  • 1,033
  • 1
  • 10
  • 31