2016-01-03 41 views
0

我有一個函數open.account,它採用參數'total'並創建三個函數(存款,取款,餘額)的列表。如果我運行test <- open.account(100)如何在不調用列表函數之一的情況下直接訪問總測試的值?如何顯示由函數創建的列表對象的參數值

open.account <- function(total) { 
    list(
    deposit = function(amount) { 
     if(amount <= 0) 
     stop("Deposits must be positive!\n") 
     total <<- total + amountw 
     cat(amount, "deposited. Your balance is", total, "\n\n") 
    }, 
    withdraw = function(amount) { 
     if(amount > total) 
     stop("You don't have that much money!\n") 
     total <<- total - amount 
     cat(amount, "withdrawn. Your balance is", total, "\n\n") 
    }, 
    balance = function() { 
     cat("Your balance is", total, "\n\n") 
    } 
) 
} 

回答

2

每個返回的函數都有自己的環境,其中total存儲在其中。

g <- open.account(total = 100) 

environment(g$deposit) 
# <environment: 0x279d0b0> 
ls(environment(g$deposit)) 
# [1] "total" 
environment(g$deposit)$total 
# [1] 100 
相關問題