pythonでクラスで構築された拡張
-
20-08-2019 - |
質問
どのように私はPythonで組み込みクラスを拡張することができますか?
私は、strのクラスにメソッドを追加したいと思います。
私はいくつかの検索を行ってきたが、私は見つけることだすべては古い記事ですが、私は誰かが新しい何かを知っている願っています。
解決
ただ、サブクラスタイプ
>>> 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
他のヒント
一つの方法は、クラスのデコレータを使ってPythonで実装することができる「クラス再開」という概念(ネイティブRubyで既存の)を使用することができます。 exempleは、このページに記載されています。 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
あなたは組み込みのクラスを変更することはできませんと仮定。
mappingproxyオブジェクトとdictのないオブジェクト__dict__
あるのpython3にルビーのように「再オープンクラス」をシミュレートするには:
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
私も同様にデコレータ機能「オープン」を書くことができます:
def open(cls):
def update(extension):
namespace = dict(cls.__dict__)
namespace.update(dict(extension.__dict__))
return type(cls.__name__,cls.__bases__,namespace)
return update
所属していません StackOverflow