如何在python中扩展内建类?我想向str类添加一个方法。
我已经做了一些搜索,但我发现所有的老帖子,我希望有人知道一些新的东西。
发布于 2008-12-09 12:08:35
只需将该类型子类化
>>> class X(str):
... def my_method(self):
... return int(self)
...
>>> s = X("Hi Mom")
>>> s.lower()
'hi mom'
>>> s.my_method()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in my_method
ValueError: invalid literal for int() with base 10: 'Hi Mom'
>>> z = X("271828")
>>> z.lower()
'271828'
>>> z.my_method()
271828
发布于 2015-10-09 16:37:13
一种方法是使用“类重新打开”概念(Ruby中固有的),该概念可以使用类装饰器在Python中实现。本页给出了一个示例:http://www.ianbicking.org/blog/2007/08/opening-python-classes.html
我引述如下:
我认为使用类装饰器可以做到这一点:
@extend(SomeClassThatAlreadyExists)
class SomeClassThatAlreadyExists:
def some_method(self, blahblahblah):
stuff
实现方式如下:
def extend(class_to_extend):
def decorator(extending_class):
class_to_extend.__dict__.update(extending_class.__dict__)
return class_to_extend
return decorator
发布于 2016-09-27 01:39:31
假设你不能改变内建类。要在Python3中模拟类似Ruby的“类重新打开”,其中__dict__
是一个映射代理对象,而不是dict对象:
def open(cls):
def update(extension):
for k,v in extension.__dict__.items():
if k != '__dict__':
setattr(cls,k,v)
return cls
return update
class A(object):
def hello(self):
print('Hello!')
A().hello() #=> Hello!
#reopen class A
@open(A)
class A(object):
def hello(self):
print('New hello!')
def bye(self):
print('Bye bye')
A().hello() #=> New hello!
A().bye() #=> Bye bye
在Python2中,我也可以写一个'open‘装饰器函数:
def open(cls):
def update(extension):
namespace = dict(cls.__dict__)
namespace.update(dict(extension.__dict__))
return type(cls.__name__,cls.__bases__,namespace)
return update
https://stackoverflow.com/questions/352537
复制相似问题