Python建立類別與實體化物件

Python建立類別與實體化物件

Python建立類別與實體化物件

 

 

資料來源: https://github.com/stormzhang/free-programming-books/blob/master/assets/python/Python%E6%A0%B8%E5%BF%83%E7%BC%96%E7%A8%8B%EF%BC%88%E4%B8%AD%E6%96%87%E7%AC%AC%E4%BA%8C%E7%89%88%EF%BC%89%E5%B8%A6%E7%9B%AE%E5%BD%95.pdf 的p52~p54

 

# -*- 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()#顯示成員變數值

 

 

 

 

 

 

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *