2017年10月3日 星期二

Python - OOP筆記

宣告方式

class Dog():
    
    species = 'mammal'

    def __init__(self, name): # 初始化方法
        self.name = name
        print("{} has been created".format(self.name))

mydog = Dog("Blacky") 
print(mydog.mammal) # 類別屬性Class Attribute
print(Dog.mammal) # 類別屬性Class Attribute
print(mydog.name) # 實例(物件)屬性Instance Attribute



例子圓形類別,計算圓面積
class Circle():
pi = 3.14

def __init__(self, radius=1):
self.radius = radius

def area(self):
return (self.radius ** 2) * Circle.pi  # 圓面積公式需要特別註明是哪種類型的屬性

tiny = Circle(2)
print(tiny.area()) 



類別變數Counter為例

class Person:
count = 0
def __init__(self):
Person.count += 1
print(Person.count)

tom = Person()
jack = Person()
amy = Person()


繼承
class Person(Alien, God, Monster):  #可實行多重繼承


封裝
利用雙底線__來封裝變數

class Person:

def __init__(self, a=2, b=3):
self.__a=a
self.__b=b

def do(self):
print(self.__a + self.__b)


呼叫父類別的建構子
class Father():
    def __init__(self):
        print("last name Hsieh")

class Son(Father):
    def __init__(self):
        Father.__init__(self)
        print("Son created")



class Father():
    def __init__(self):
        print("last name Hsieh")

class Son(Father):
    def __init__(self):
        super(Son, self).__init__()
        print("Son created")



特別method名稱

class Book():
def __init__(self, name, pages):
self.name = name
self.pages = pages
def __str__(self):
return "Name:{}".format(self.name)
def __len__(self):
return self.pages
def __del__(self):
print("A book is deleted.")

b = Book("The Guide", 20)

print(b) # __str__
print(len(b)) # __len__
del b # __del__
更多參考https://openhome.cc/Gossip/Python/SpecialMethodNames.html

沒有留言:

張貼留言