[英]Keep one variable the same within the class (with multiple functions) for reuse elsewhere
我有一個 class 腳本( secondary.py
),當在我的main.py
文件中調用它時,它可以工作。 我的問題是我想在另一個腳本tertiary.py
中調用下面的第二個 function ,並且 output 變量reg_name
對於下面的兩個函數都相同 -
import pandas as pd
import re
# Class to keep randomly pulled name the same throughout ----
class NameHandle():
# init
def __init__(self):
# reads in csv with a celeb's name in one col & their twitter handle in the second col - e.g. name: Oprah & handle: @oprah
# kicker: since the row is randomly chosen, it *needs* to stay the same throughout
handle_csv = pd.read_csv('handle_list.csv')
ran_line = handle_csv.sample(n = 1, replace = False)
self.reg_name = ran_line['name'].to_string()
print("test one" + self.reg_name) ### test print
self.handle_tag = ran_line['handle'].to_string()
# format randomly pulled celeb name and twitter handle
def name_and_handle(self):
# create & format sentence, to send back to main.py
print("test two" + self.reg_name) ### test print
sentence = self.reg_name + "'s Twitter handle is" + ' ' + self.handle_tag
sentence = re.sub(r'\d+', '', sentence)
sentence = " ".join(re.split("\s+", sentence, flags = re.UNICODE))
return sentence
# function to keep celeb name the same through the entire process
def name_insurance(self):
same_name = self.reg_name
print("test three" + same_name) ### test print
return same_name
# Main function ----
if __name__ == '__main__':
NameHandle().name_and_handle()
NameHandle().name_insurance()
如果我在main.py
腳本中調用 function name_and_handle()
- 它可以工作。 如果我在主腳本或任何其他腳本中調用第二個 function, name_insurance()
,我會得到一個不同的名稱,而不是相同的名稱。 三個print()
語句證實了這一點。 我錯過了一些簡單的東西 - 對課程來說非常新 - 如果這是一個愚蠢的問題,請在下面將我釘在十字架上,我將刪除。
# Calling `secondary.py` in `main.py`
import secondary as sd
# outputs different names
sd.NameHandle().name_and_handle()
sd.NameHandle().name_insurance()
因此,您得到了ran_line = handle_csv.sample(n = 1, replace = False)
這意味着每次創建 class NameHandler
的新實例時都會得到一條隨機線。
每次您NameHandle()
時,您都在創建一個新實例,因此,得到一個新的隨機行。
只需創建一次 class 實例並使用該實例調用函數。
name_handle_instance = sd.NameHandle()
name_handle_instance.name_and_handle()
name_handle_instance.name_insurance()
我不知道為什么它會在__main__
下工作,但在導入時卻不行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.