@MartijnPieters answer
_key_type_global = unicode
class A(dict):
_key_type = unicode
def __setitem__(self, key, value):
"""A._key_type is not recognised, _key_type_global is
:type key: _key_type_global
:type value: int
"""
super(A, self).__setitem__(key, value)
class B(A): pass
a = A()
a['str'] = 'uy' # expected type unicode got str instead
a[u'str'] = 'uy' # no warn (?)
a[u'str'] = 1 # no warn
val = a[u'str'] # Pycharm does not give any type info on value so I have to
# define __getitem__ too
# type info is inherited
b = B()
b['str'] = 'uy' # expected type unicode got str instead
b[u'str'] = 'uy' # no warn (?)
b[u'str'] = 1 # no warn
だから1は、すべてのメソッドをオーバーライドする必要があります(私は、以下の動作が原因標準またはIDEのバグ/機能であってよいPycharm 5.0.4を使用しています)(キーにエラボレーション値型情報は個々のメソッドに対してローカルです)。 IOWは、1が行うことができますパラメータや属性などのためのケースとは異なり:
class A(dict): # type dict[unicode, int]
はさらに種類を指定できるようにする手立てがないように思える:
class A(object):
def __init__(self, dct):
self.dct = dct # type : dict[unicode, int]
これはNOOPですクラス変数として、サブクラスで簡単にオーバーライドすることができます。
*「タイプコメント」*とはどういう意味ですか?あなたは実際に型を強制したいのですか、それとも単にドキュメント化したいのですか? – jonrsharpe
@jonrsharpe:[PEP 484 *タイプコメント*](https://www.python.org/dev/peps/pep-0484/#type-comments) –
@MartijnPietersああありがとう、私はOPが参考にしていたかどうか疑問に思ったドキュメンタリーや何かに – jonrsharpe