__init__構造函數

# -*- coding: utf-8 -*-
class Document():
    def __init__(self, title, author, context):
     print('init function called')
     self.name='xxx'



harry_potter_book = Document('Harry Potter', 'J. K. Rowling', '... Forever Do not believe any thing is capable of thinking independently ...')

print(harry_potter_book.name)

C:\Python27\python.exe "C:/Users/TLCB/PycharmProjects/untitled2/python study/t15.py"
init function called
xxx


如果去掉__init__:

# -*- coding: utf-8 -*-
class Document():
    # def __init__(self, title, author, context):
     print('init function called')
     self.name='xxx'



harry_potter_book = Document('Harry Potter', 'J. K. Rowling', '... Forever Do not believe any thing is capable of thinking independently ...')

print(harry_potter_book.name)

C:\Python27\python.exe "C:/Users/TLCB/PycharmProjects/untitled2/python study/t15.py"
init function called
Traceback (most recent call last):
  File "C:/Users/TLCB/PycharmProjects/untitled2/python study/t15.py", line 2, in <module>
    class Document():
  File "C:/Users/TLCB/PycharmProjects/untitled2/python study/t15.py", line 5, in Document
    self.name='xxx'
NameError: name 'self' is not defined

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章