Created
October 30, 2010 07:26
-
-
Save t9md/655060 to your computer and use it in GitHub Desktop.
python's class attribute and function attribute named method
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
#!/usr/bin/env python | |
# -*- coding: utf8 -*- | |
# クラス | |
class Spam(object): | |
"""docstring for Spam""" | |
# クラス属性 | |
class_atrr = "This is class attribute" | |
# __init__ がコンストラクタ。第一引数で作られたばかりのインスタンスを受けとる。 | |
def __init__(self, name): | |
# スーパークラスのコンストラクタを呼ぶ | |
super(Spam, self).__init__() | |
self.hello = "hello " + name | |
# メソッドとは、クラス属性の特別な形態に過ぎない。 | |
# それは、第一引数にレシーバオブジェクトをとる関数。 | |
# この関数は直接呼ぶ事も出来る。 | |
# クラス属性として設定すると、メソッドと呼ばれる。 | |
# メソッドになると、selfで受けとるレシーバは自動的に渡されるので | |
# 明示的に渡す必要はなくなる。 | |
def special_function(self): | |
"""docstring for special_function_called_as_method""" | |
return self.__doc__ | |
spam = Spam('t9md') | |
# __doc__ で docstring にアクセス可能 | |
print Spam.__doc__ # => docstring for Spam | |
print '----' | |
# クラス属性を参照。 | |
print spam.class_atrr # => This is class attribute | |
# オブジェクト経由でも参照できる。 | |
print spam.class_atrr # => This is class attribute | |
print '----' | |
# インスタンス属性を設定。 | |
spam.class_atrr = "Is this class attribute?" | |
# インスタンス属性が優先的に見つかる。 | |
print spam.class_atrr # => Is this class attribute? | |
# クラス経由での参照。こちらは影響を受けない。 | |
print Spam.class_atrr # => This is class attribute | |
print '----' | |
# インスタンス属性を消す。 | |
del spam.class_atrr | |
# インスタンス属性が無ければ,クラス属性が姿を現す。 | |
print spam.class_atrr # => This is class attribute | |
print '----' | |
# メソッドになる前の普通の関数。Spam クラスのインスタンスである spam を引数として渡す。 | |
print special_function(spam) # => docstring for Spam | |
# メソッドにする! | |
Spam.doc = special_function | |
# doc メソッドを呼ぶ。 | |
print spam.doc() # => docstring for Spam | |
print spam.hello # => hello t9md |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment