Python 的類和對象

 

首先我們來談談 self 是什麼。

看過上一章節的人,肯定會有一個疑問,為什麼def + function 後面要再加一個(self) ?

很簡單,其實pythonself就相當於C++this指針。

 

 

Python的類很神奇,它會自己帶一些你沒寫的方法(method)進去,EX: __init__(self)

 

__init__(self) = 構造方法 ( 構造函數 ),只要實例化一個object的時候,那麼這個方法就會在創鍵的時候,自動的被調用。

 

class Ball:

    #重寫init

    def __init__(self,name = 'Eric'):

        self.name = name;

    def kick(self):

        print("我叫%s ,該死的誰踢我 ? " %self.name)





a = Ball('A');



b = Ball();



c = Ball('C');





a.kick();

b.kick();

c.kick();

 

 

私有變量

      python定義私有變量,只需要再變量名或函數名稱前面加上__ 兩個底線,那麼它就會是一個私有變量囉。

 

class Person:

    __name = 'Eric'     #__name = private

    def GetName(self):

        return self.__name;



p = Person()

print(p.GetName())

print(p._Person__name)

 

 

 

 

 

繼承

+名稱+(父類)

Class MyNewClass(BaseClassName)

class Parent:

    def hello(self):

        print('Invoke Parent Class');



class Child(Parent):

    pass





p = Parent()

p.hello()



c = Child()

c.hello()

這樣結果 = 印出兩個Invoke Parent Class

如果子類中定義與父類同名的方法或屬性,則會自動復蓋掉父類對應的方法或屬性。

class Parent:

    def hello(self):

        print('Invoke Parent Class');



class Child(Parent):

    def hello(self):

        print('Invoke Child Class');





p = Parent()

p.hello()



c = Child()

c.hello()

 

會印出:

Invoke Parent Class

Invoke Child Class

 

 

繼承

import random as r



class Fish:

    def __init__(self):

        self.x = r.randint(0,10);

        self.y = r.randint(0,10);



    def move(self):

        self.x -=1;

        print("我的位置是: ",self.x,self.y);



class GoldFish(Fish):

    pass

class Carp(Fish):

    pass

class Salmon(Fish):

    pass



class Shark(Fish):

    def __init__(self):

        Fish.__init__(self)

        self.hungry = True;



    def eat(self):

        if(self.hungry):

            print("吃貨的夢想就是天天有得吃 !")

            self.hungry = False;

        else:

            print("太撐了  剛吃飽")



fish = Fish()

fish.move()

fish.move()



goldfish = GoldFish()

goldfish.move()



shoark = Shark()

shoark.eat()

shoark.eat()

# shoark.move()     AttributeError: 'Shark' object has no attribute 'x'

# 因為重寫了__init__這個屬性,所以父類的__init__被改寫掉了

# 這邊可以用 Fish.__init__(self)來解決這個問題

shoark.move()

 

 

多重繼承

class Base1:

        def foo1(self):

            print("Invoke foo1 ")



class Base2:

        def foo2(self):

            print("Invoke foo2")





class C(Base1,Base2):

    pass



c = C()

c.foo2()

c.foo1()

 

 

 

組合方式 :

class Turtle:

    def __init__(self ,x ):

        self.num = x ;

class Fish:

    def __init__(self, x):

        self.num = x ;



class Pool:

    def __init__(self,x,y):

        self.turtle = Turtle(x)

        self.fish  = Fish(y)

    def print_num(self):

        print("水池裡總共有烏龜 %d , 小魚:%d " %(self.turtle.num,self.fish.num))





pool = Pool(1,10)

pool.print_num()

 

 

arrow
arrow
    文章標籤
    python class object
    全站熱搜

    Eric 發表在 痞客邦 留言(0) 人氣()