close

 

Private & Public   

import os
import sys
import copy
from functools import reduce

class Bank():
    def __init__(self,uname):
        self.__name = uname             #private
        self.__balance = 600              #private
        self.__backname= 'Eric bank'    #private
        self.msg = 'Hello world'        #public

    def save_money(self,money):
        self.__balance += money
        print(money)
    def withdraw_money(self,money):
        self.__balance -= money
        print(money)
    def get_balance(self):
        print(self.__name.title(), self.__balance)


def main():
    Item = Bank('Eric')
    print(Item.msg)     #can work, print "Hello world"
    #print(Item.__name)  #'Bank' object has no attribute '__name'
    print(Item.get_balance())   # Hello world
                                # Eric 0
                                # None



    '''
        其實,Python private並不是那麼的安全,因為像以下的方式,
        其實還是可以設定private的變數,所以,在設定private name的時候
        就必須要小心點
    '''
    Item._Bank__balance = 120000
    Item.get_balance()          #Eric 120000


if (__name__=='__main__'):
    main()

 

 

Private Method

import os
import sys
import copy
from functools import reduce

class Bank():
    def __init__(self,uname):
        self.__name = uname             #private
        self.__balance = 600              #private
        self.__backname= 'Eric bank'    #private
        self.msg = 'Hello world'        #public
        self.__service_charge = 0.01
        self.__rate = 30


    def save_money(self,money):
        self.__balance += money
        print(money)
    def withdraw_money(self,money):
        self.__balance -= money
        print(money)
    def get_balance(self):
        print(self.__name.title(), self.__balance)

    '''
    既然class private的屬性,那一定也有privatemethod,他的觀念其實和private屬性類似,
    就是不想讓外部程式來呼叫,而使用方法也很容易,就是在方法前面加上 __(兩個底線)就可以了
    '''
    def __cal_rate(self,usa_d):
        return int(usa_d*self.rate * 1(1-self.__service_charge))


def main():
    Item = Bank('Eric')
    print(Item.msg)     #can work, print "Hello world"
    #print(Item.__name)  #'Bank' object has no attribute '__name'
    print(Item.get_balance())   # Hello world
                                # Eric 0
                                # None



    '''
        其實,Python private並不是那麼的安全,因為像以下的方式,
        其實還是可以設定private的變數,所以,在設定private name的時候
        就必須要小心點
    
    Item._Bank__balance = 120000
    Item.get_balance()          #Eric 120000
    '''

    # 破解private method 的方式
    print(Item.__cal_rate(50)) #這邊會報錯
    print(Item._Bank__cal_rate(50)) #這邊就會過了


if (__name__=='__main__'):
    main()

 

arrow
arrow
    全站熱搜

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