Created
December 5, 2013 14:02
-
-
Save 0xfffffff7/7805585 to your computer and use it in GitHub Desktop.
Pythonのクラスメンバのスコープまとめ ref: http://qiita.com/0xfffffff7/items/6ef16e79fe9886acb3f2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
class Widget(object): | |
# コンストラクタ | |
def __init__(self, r, l): | |
# 通常メンバ変数 | |
self.rval = r | |
self.lval = l | |
# プライベート変数 | |
self.__secret = 5 | |
# publicクラスメンバ変数 | |
classVal = 30 | |
# プライベートクラス変数 | |
# 外からは特別な記述でないとアクセスできない | |
__SecretClassVal = 10 | |
# 通常メソッド | |
def Calc(self): | |
# ここでもメンバ変数を定義できる。 | |
self.top = 10 | |
return self.rval * self.lval * self.top | |
# プライベートメソッド | |
def __MyCalc(self): | |
print "This is Private Method!" | |
# クラスメソッド. | |
@classmethod | |
def SelfName(cls): | |
# ここでもクラスメンバ変数の定義ができる。 | |
cls.number = 1 | |
# プライベートクラスメソッド. | |
@classmethod | |
def __PrivateSelfName(cls): | |
print "This is Private Class Method!" | |
if __name__ == '__main__': | |
# コンストラクタと通常メソッドの呼び出し。 | |
w = Widget(2, 4) | |
# メンバ変数へのアクセス | |
w.lval = 3 | |
w.rval = 4 | |
# プライベートメンバ変数にアクセス。 | |
# インスタンス._クラス名__変数名でアクセスできる。(推奨されない) | |
print w._Widget__secret | |
# パプリッククラス変数へアクセス。 | |
# インスタンス名でもクラス名でもどちらでもアクセス可能。 | |
print Widget.classVal | |
print w.classVal | |
# プライベートクラス変数にアクセス。 | |
# インスタンス._クラス名__変数名でアクセスできる。(推奨されない) | |
print w._Widget__SecretClassVal | |
# 通常のメソッドの呼び出し. | |
print w.Calc() | |
# プライベートメソッドの呼び出し(推奨されない) | |
print w._Widget__MyCalc() | |
# クラスメソッドの呼び出し. | |
Widget.SelfName() | |
# プライベートクラスメソッドの呼び出し(推奨されない) | |
print w._Widget__PrivateSelfName() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment