Extending builtin classes in python

前端 未结 3 594
情歌与酒
情歌与酒 2020-12-13 14:02

How can I extend a builtin class in python? I would like to add a method to the str class.
I\'ve done some searching but all I\'m finding is older posts, I\'m hoping s

3条回答
  •  误落风尘
    2020-12-13 14:46

    Just subclass the type

    >>> 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 "", line 1, in 
      File "", 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
    

提交回复
热议问题