Pythonã§Classã®__init__ã¡ã½ããã®ç¶æ¿ã試ãã
Pythonã§Classã®ã¤ã³ã¹ã¿ã³ã¹åããæã®ã³ã³ã¹ãã©ã¯ã¿ã§ãã__init__ã¡ã½ããã®ç¶æ¿ã試ãã¦è¦ã¾ããã
ã¾ãFirstã¯ã©ã¹ãã¤ã³ã¹ã¿ã³ã¹åããã¨xã¨yã®å¤ãè¨å®ããã¾ãã次ã«Firstã¯ã©ã¹ã親ã¨ããSecondã¯ã©ã¹ãã¤ã³ã¹ã¿ã³ã¹åããå ´åã«xã¯è¦ªãç¶æ¿ãyã¯Secondç¨ã®å¤ã§ä¸æ¸ããããã«zãæ°è¦è¿½å ããã¨ããå¦çããã¦ãã¾ãã
ã½ã¼ã¹ã³ã¼ã
class First(object): def __init__(self): self.x = "first init x" self.y = "first init y" class Second(First): def __init__(self): First.__init__(self) # SuperClassã§ããFirstã®__init__ã¡ã½ãããå®è¡ self.y = "second init y" # First.yã®å¤ãSecond.yã®å¤ã§ä¸æ¸ã self.z = "second init z" # Firstã¯ã©ã¹ã«åå¨ããªãå¤ãSecond.zã¨ãã¦è¿½å ãã if __name__ == '__main__': hoge = First() print "hoge.x: %s" % hoge.x print "hoge.y: %s" % hoge.y fuga = Second() print "fuga.x: %s" % fuga.x print "fuga.y: %s" % fuga.y print "fuga.z: %s" % fuga.z
å®è¡çµæ
macbook:lab ox$ python hoge.py hoge.x: first init x hoge.y: first init y fuga.x: first init x # ç¶æ¿ fuga.y: second init y # ä¸æ¸ã fuga.z: second init z # æ°è¦è¿½å
ãã¼ã便å©ã