2017-11-04 38 views
-1

這2個問題滾入1 - 我從旁邊的腳本如下輸出你如何管理在Python功能範圍和同步3

Checker: start of thread 
Checker: (0) Hello, world 
Checker: (1) Hello, world 
Checker: (2) How do you do 
Checker: (3) How do you do 
Checker: start of thread 
Checker: (4) Bye for now 
Checker: exiting thread 
Checker: (0) Bye for now 
Checker: exiting thread 

腳本:

#!/usr/local/bin/python                               

import time 
import threading 

class CheckTscope: 

def __init__ (self): 
    self.name = 'checker' 
    self.msg = None 

def checker (self, msg="Hey stranger"): 
    count = 0 
    self.setMessage(msg) 
    print ("Checker: start of thread") 
    while True: 
     time.sleep (0.04) 
     print ("Checker: (", count, ")", self.getMessage()) 
     if self.carry_on: 
      count += 1 
      continue 
     break 
    print ("Checker: exiting thread") 

def getMessage (self): 
    return self.msg 

def setMessage (self, text): 
    self.msg = text 

def construct (self, initxt): 
    self.setMessage (initxt) 
    self.carry_on = True 
    reporter = threading.Thread(target=self.checker, args=(initxt,)) 
    reporter.start() 

def destruct (self): 
    self.carry_on = False 


if __name__ == '__main__': 
    ct = CheckTscope() 
    ct.construct("Hello, world") 
    time.sleep(0.125) 
    ct.setMessage("How do you do") 
    time.sleep(0.06) 
    ct.destruct() 
    time.sleep(0.02) 
    ct.checker ("Bye for now") 

的問題:

  1. 如何使函數checker()只能訪問此類中的其他函數(限制t他的範圍)?

  2. 如何同步多個線程(「4 - 現在再見」是一個錯誤,當消息設置爲新值時計數器應該重置)。

本質上,我正在尋找替換「同步私人無效」從另一種語言。感謝您的幫助。

+0

您可以使用**下劃線**來創建一個變量或方法private.at,至少一個用於變量(_somevar),至少兩個用於'methods'(__someMethod).see here => https:// docs .python.org/3/tutorial/classes.html#private-variables – shotgunner

+0

Python並沒有真正的私有屬性或方法。您可以使用_single_前導下劃線來標​​記私有屬性或方法,但這僅僅是一種約定,Python不會對這些對象實施任何條件。口號是「我們都在這裏同意大人」。 –

+0

@shotgunner我不知道你在哪裏學到了這些,但它不正確。請參閱[對象名稱前的單下劃線和雙下劃線的含義是什麼?](https://stackoverflow.com/questions/1301346/what-is-the-meaning-of-a-single-and -a-double-underscore-before-an-object-name) –

回答

0

1 - 你沒有。方法和變量的範圍大部分時間都是由編程約定來處理的。在這種情況下,您應該在檢查器的開始處添加一個下劃線,以將其識別爲只應由班內其他方法調用的私有方法。 2 - 要使用線程特定命令與線程同步多個線程,試圖像使用「carry_on」一樣使用,會讓你在一些奇怪的小巷中結束。 Ps:如果我記得有@Async和@Sync註釋,您可以進一步瞭解它。

+0

謝謝。 「你不能做到這一點」是一個完全有效的答案:) –

+0

Python是非常寬容的,所以我們很大程度上依賴於良好的實踐和慣例,pep等 –

+0

亂搞我的代碼和閱讀這裏的東西 - 我想,改變方法從checker到__checker的名稱解決了1個問題(使其成爲私有) - 錯誤:「AttributeError:'CheckTscope'對象沒有屬性'__checker'」。 –