Chapter 10 Object Oriented Programming

  1. Class and instance

  2. Attributes

  3. Instance method and static method

10.3 Class attributes and instance attributes

  • 透過def __init__(self,...)定義的attribute為instance attributes.

  • 其他def __init__(self,...)以外定義的object都會成為class attributes.

    class attribute自然會是instance attribute

以下何者為class attr?何者為instance attr?

在一個父姓社會,定義linFamily這個class,每個instance是一個人:

  • 所有的instance一定姓“林”:即self.surname="林"

  • 每個instance有自己的名:即self.firstname因人而異

  • 每個instance有自己的性別:即self.gender因人而異

  • 每個instance print時會顯示“我叫XXX, 性別Y”

10.4 Instance method

  • Instance method: def ...(self,...): 第一個arg為self. self代表了instance本身。

An instance method is defined whenever a function definition is specified within the body of a class. This may seem trivial but there is still a significant nuance that must be cleared up, which is that ‘self’ is the defacto first-argument for any instance method.

When you call an instance method (e.g. func) from an instance object (e.g. inst), Python automatically passes that instance object as the first argument, in addition to any other arguments that were passed in by the user.

因此每個class body裡的def最好都加上self成第一個input。

在Basic concept範例裡,指出當中的instance method/static method。

延續linFamily class。

  • 每個林家人有marry method,即instance.marry(spouse)。此method會增加instance.spouse屬性。
## {'surname': '陳', 'familyname': '小美', 'gender': '女'}

10.4.1 範例

抽出

  • Sample size: 100個觀測值

  • Model: 來自\(y=0.1x+0.33\epsilon\).

  • Distribution: 分配\(x\perp\epsilon,\ x,\epsilon\sim N(0,1)\)

產生一組樣本牽涉到以上3個元素。從OOP角度來看,「產生一組樣本」這類(class)的事,需要有Sample size, model, 及distribution三個屬性(attributes)來定義。

從OOP角度定義「產生一組來自\(y=0.1x+0.33\epsilon\)\(x,y\)服從標準常態分配」這類的事:

  • 屬性只有Sample size

對於:

假設\(y=X\beta+\epsilon\),其中\(X,\epsilon\)為獨立標準常態分配隨機變數。若以\(f(X)=X\beta\)為預測模型去預測\(y\),並使用OLS來選\(\beta\)參數,其預測準確度會不會受不同真實\(\beta\)值影響

這類的事情,你需要的元素有:

  • beta, sample size:

  • data:

  • split data: training set, test set

  • fit: model fitting, 即estimation

  • predict

請完成fit及predict method

10.6 Static method

  • static method: def ...(....): 沒有用self(或cls,以後會講class method)在arg裡。

A static method is simply a method whose arguments must all be passed explicitly by the user. That is, Python doesn’t pass anything to a static method automatically.

A static method is simply a method whose arguments must all be passed explicitly by the user. That is, Python doesn’t pass anything to a static method automatically. The built-in decorator @staticmethod is used to distinguish a method as being static rather than an instance method.

10.7 Some tricks

10.7.1 Add/modify an attribute of an instance

You can add or modify an attribute to an instance via:

instance.variable = value

Example

instance新增或修改的attribute不會增加或修改到其他instance。