[英]How to instantiate an object which belongs to another class without importing
我正在 Python 進行銀行管理系統項目的第二部分。我創建了 4 個模塊:person.py、bank_account.py、bank_card.py 和 main.py
我還為以下每個模塊創建了 3 個類:個人 Class、銀行賬戶 Class 和銀行卡 class。
我被要求在 Bank_Account class 下創建一個 new_card class function。為此,我已將銀行卡 class 導入(因為我在這里被允許)到 bank_account.py 模塊中。 在這一點上沒問題。 這是我的銀行賬戶 class 中用於我的新卡 function 的代碼:
def new_card (self,card_number, month, year, cvv, pin_code):
card1 = Bank_Card(card_number,month,year,cvv,pin_code)
self.__bank_card = card1
return card1
我掙扎的地方是當任務請求在 main.py 中創建一張卡片 object 時。 我不允許將銀行卡導入main.py但我需要使用在 Bank_Account class上定義的function new_card 創建卡 object。當我試圖通過在main.py中創建 card2 來這樣做時,我不能像 card2.new_card 一樣調用 new_card function因為沒有導入 Bank_Card class:(
有任何想法嗎?
我已經添加了到目前為止我的代碼看起來如何的屏幕截圖......如果我按照建議進行(調用方法 Bank_Account.new_card(),那么我會收到一條錯誤消息,指出缺少 arguments。
我希望這張圖片可以幫助您更清楚地了解我面臨的問題
您不需要在主程序中導入Bank_Card
class,因為它在Bank_Account
class 中間接可用。據我從問題中了解到,您需要做的就是將Bank_Account
class 從“bank_account.py”導入主程序“ 模塊。
這就是您實現相同目標的方式:
## File: "main.py"
# Import the Bank Account class from the module
from bank_account import Bank_Account
# Define the card details which will be used for creating the card
# You may provide the details inline to the method call if you want
card_number = ...
month = ...
year = ...
cvv = ...
pin_code = ...
# Create a new bank card instance by calling the `new_card` method
my_card = Bank_Account.get_card(card_number, month, year, cvv, pin_code)
在這里,我們從bank_account.py
模塊導入Bank_Account
class,然后調用在 class 上創建的new_card()
方法。這將返回一個新的 Bank Card 實例,您可以按預期使用它。 不幸的是,調用Bank_Account.get_card()
方法時會拋出錯誤,因為new_card
不是 static 方法。 為了解決這個問題,您需要將 new_card 方法裝飾為new_card
方法,如下所示:
class Bank_Account:
...
@staticmethod
def new_card(card_number, month, year, cvv, pin_code):
...
請注意, self
參數已從new_card()
方法中刪除,因為它不需要 Bank_Account class 的Bank_Account
,而是可以使用 class 本身直接調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.