首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在python中扩展内置类

在python中扩展内置类
EN

Stack Overflow用户
提问于 2008-12-09 12:01:30
回答 3查看 23.7K关注 0票数 36

如何在python中扩展内建类?我想向str类添加一个方法。

我已经做了一些搜索,但我发现所有的老帖子,我希望有人知道一些新的东西。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2008-12-09 12:08:35

只需将该类型子类化

代码语言:javascript
复制
>>> 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
票数 36
EN

Stack Overflow用户

发布于 2015-10-09 16:37:13

一种方法是使用“类重新打开”概念(Ruby中固有的),该概念可以使用类装饰器在Python中实现。本页给出了一个示例:http://www.ianbicking.org/blog/2007/08/opening-python-classes.html

我引述如下:

我认为使用类装饰器可以做到这一点:

代码语言:javascript
复制
@extend(SomeClassThatAlreadyExists)
class SomeClassThatAlreadyExists:
    def some_method(self, blahblahblah):
        stuff

实现方式如下:

代码语言:javascript
复制
def extend(class_to_extend):
    def decorator(extending_class):
        class_to_extend.__dict__.update(extending_class.__dict__)
        return class_to_extend
    return decorator
票数 14
EN

Stack Overflow用户

发布于 2016-09-27 01:39:31

假设你不能改变内建类。要在Python3中模拟类似Ruby的“类重新打开”,其中__dict__是一个映射代理对象,而不是dict对象:

代码语言:javascript
复制
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‘装饰器函数:

代码语言:javascript
复制
def open(cls):
  def update(extension):
    namespace = dict(cls.__dict__)
    namespace.update(dict(extension.__dict__))
    return type(cls.__name__,cls.__bases__,namespace)
  return update
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/352537

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档