問題解説)PEP8の継承の説明について、間違っているものを次の選択肢の中から選びなさい。

当コラムでは、PythonZen & PEP 8 検定試験(こちらでオンライン受験できます)で出題されている問題の解説を行なっています。当コラムシリーズを読んで自信がついたら、ぜひ試験に挑戦してみてくださいね。

今回のコラムで解説する試験問題はこちらです。

問題

PEP8の継承の説明について、間違っているものを次の選択肢の中から選びなさい。

  1. クラスの属性(メソッドやインスタンス変数など)を公開するかどうか迷った時は、非公開にしておく。
  2. 公開している属性については後方互換性を壊さないように変更されるべきだが、非公開の属性についてはその限りではない。
  3. 公開している属性が予約語と衝突してしまう場合は、公開属性の先頭にアンダースコアをつける。
  4. Pythonにはアクセス修飾子がないため、サブクラスで使用して欲しくない属性の先頭にはアンダースコアを2つつける。

解答のヒント

PEP 8の「継承の設計」(Designing for Inheritance)が問題の範囲になっています。

Always decide whether a class’s methods and instance variables (collectively: “attributes”) should be public or non-public. If in doubt, choose non-public; it’s easier to make it public later than to make a public attribute non-public.

クラスのメソッドやインスタンス変数(合わせて「属性 = attributes」と言う)は、必ず公開(public)か非公開(publicでない)かを決めてください。公開属性を非公開に変更するよりも、非公開属性を後から公開に変更する方が簡単です。

Public attributes are those that you expect unrelated clients of your class to use, with your commitment to avoid backwards incompatible changes. Non-public attributes are those that are not intended to be used by third parties; you make no guarantees that non-public attributes won’t change or even be removed.

公開属性とは、そのクラスを書いた人とは無関係なクライアントに使用されることを想定したものですので、後方互換性を保つことが約束されています。一方、非公開属性は第三者が使用することを想定していない属性ですので、変更や削除をしないという保証はありません。

Public attributes should have no leading underscores.
If your public attribute name collides with a reserved keyword, append a single trailing underscore to your attribute name. This is preferable to an abbreviation or corrupted spelling.

公開属性は、先頭にアンダースコアをつけないようにします。
公開属性の名前が予約キーワードと衝突する場合は、属性名の末尾にアンダースコアを1つ追加してください。これは、属性名を略したり間違ったスペルにするよりも望ましい方法です。

If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores. This invokes Python’s name mangling algorithm, where the name of the class is mangled into the attribute name. This helps avoid attribute name collisions should subclasses inadvertently contain attributes with the same name.

クラスがサブクラスに継承されること想定しており、サブクラスに使わせたくない属性がある場合は、属性名の先頭にアンダースコアを2つつけること(末尾のアンダースコアはなし)を検討してください。アンダースコアを2つつけるとPythonの名前修飾アルゴリズムによって属性名にクラス名が修飾されます。これにより、サブクラスが不注意で同じ名前の属性を含んでしまった場合に、親クラスと属性名が衝突するのを避けられます。

正解はこちら

ガイドラインには、ルールとして従わなくてはいけないこと(must)、推奨されること(should)、各ルールの適用例・非適用例(cases)が書いてあります。ルールを機械的に覚えるだけではなく、なぜこのルールがあるのかを意識していくと、理解が深まりますね。

自信がついてきたら PythonZen & PEP 8 検定試験 で実際に試験を受けて、正解を当ててみましょう。

そして、みなさんのPython開発にも活かしていただけると嬉しいです。

PAGE TOP