1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Python】前にアンダースコア(アンダーバー)2つの関数って何

Last updated at Posted at 2019-11-12

classの中にある関数の前にアンダースコアが2つある時がある

    def __hogehoge():
        print('Hello.')

なんの意味があるのか知らなかったので備忘録
結論:そのclass内でしか呼び出せなくなる

練習してみる

実際にやってみよう〜
下記のようなサンプルを用意
※わかりやすように関数名はpublic、privateとしてますが稼働に際して意味はありません。

train.py
class Hoge:
    def __init__(self):
        print('this is init function.')
        
    def public():
        print('this is public function.')
    
    def __private():
        print('this is private function.')

【ターミナル】でこのファイルがあるディレクトリまで移動してから以下のように実行

Hogeクラスの実行

__init__はclassを実行すると必ず呼び出される

$python
>>> from train import Hoge 
>>> Hoge()
this is init function.

public関数の実行

ターミナルの先ほどの続きに以下のように入力

>>> Hoge.public()
this is public function.

何も付いていない関数は問題なく呼び出せる

private関数の実行

ターミナルの先ほどの続きに以下のように入力

>>> Hoge.__private()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'Hoge' has no attribute '__private'

外部からの呼び出し失敗

追記:
19/12/4
コメントいただきました。
どうしても呼び出したい場合はFoo._Foo__aとすることで呼び出せるようです!
情報ありがとうございます。

1
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?