Python建立類別與實體化物件
Python建立類別與實體化物件
# -*- coding: UTF-8 -*- #Python建立Class class FooClass(object): “””my very first class: FooClass””” version = 0.1 # class (data) attribute def __init__(self, nm=’John Doe’):#建構子 “””constructor””” self.name = nm # class instance (data) attribute print(‘Created a class instance for’, nm) def showname(self): “””display instance attribute and class name””” print(‘Your name is’, self.name) print(‘My name is’, self.__class__.__name__)#顯示類別名稱 def showver(self): “””display class(static) attribute””” print(self.version) # references FooClass.version def addMe2Me(self, x): # does not use ‘self’ “””apply + operation to argument””” return x + x
foo1 = FooClass()#將物件實體化~此時會執行建構子的輸出 foo1.showname() foo1.showver()#顯示成員變數值 print(foo1.addMe2Me(100))#呼叫成員函數做運算
foo2 = FooClass(‘jash.liao’)#將物件實體化,建構子傳入參數~此時會執行建構子的輸出 foo2.version=0.2#直接指定成員變數 foo2.showver()#顯示成員變數值 |