简体   繁体   中英

Can you modify a package's base class in python?

I've installed a python package (schematic), which has a number of classes extended from a base class.

class BaseType(object):
    def __init__(self, required=False, default=None ...)
    ...

class StringType(BaseType):
    ...

class IntType(BaseType):
    ...

I would like to be able to modify the BaseType class, so it would accept additional constructor variables.

I know I could define my own classes based on these, but I was wondering if there's actually a way in Python to modify just the base class?

Thank you, Ben

Of course you can. Simply do BaseClass.__init__ = your_new_init . This does not work if the BaseClass is implemented in C however(and I believe you cannot reliably change a special method of a class implemented in C; you could do this writing in C yourself).

I believe what you want to do is a huge hack, that will only cause problems, so I strongly advise you to not replace __init__ of a base class that you didn't even write.

An example:

In [16]: class BaseClass(object):
    ...:     def __init__(self, a, b):
    ...:         self.a = a
    ...:         self.b = b
    ...:         

In [17]: class A(BaseClass): pass

In [18]: class B(BaseClass): pass

In [19]: BaseClass.old_init = BaseClass.__init__ #save old init if you plan to use it 

In [21]: def new_init(self, a, b, c):
    ...:     # calling __init__ would cause infinite recursion!
    ...:     BaseClass.old_init(self, a, b)
    ...:     self.c = c

In [22]: BaseClass.__init__ = new_init

In [23]: A(1, 2)   # triggers the new BaseClass.__init__ method
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-23-09f95d33d46f> in <module>()
----> 1 A(1, 2)

TypeError: new_init() missing 1 required positional argument: 'c'

In [24]: A(1, 2, 3)
Out[24]: <__main__.A at 0x7fd5f29f0810>

In [25]: import numpy as np

In [26]: np.ndarray.__init__ = lambda self: 1   # doesn't work as expected
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-26-d743f6b514fa> in <module>()
----> 1 np.ndarray.__init__ = lambda self: 1

TypeError: can't set attributes of built-in/extension type 'numpy.ndarray'

You can probably edit the sourcefiles where the base class is defined, or make a copy of the package and edit the source for your specific project.

See also: How do I find the location of my Python site-packages directory?

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