[英]How do I inherit all variable from a parent class to a base class having an init function?
[英]How do i inherit the data members from parent to base class
我通過調用__init__
方法將數據成員從父類繼承到基類,但繼續收到以下錯誤消息
database_creator .__ init __(self,username,password,m_database)
NameError:未定義名稱“用戶名”
如果我沒記錯的話,上面的代碼行是用來從另一個類繼承成員的,我正在使用MySQL.connector連接到數據庫並使用類聲明來執行查詢。以下是代碼的一部分
class database_creator: # the class that connects to the database
def __init__(self , username , password , m_database):
self.username = username
self.password = password
self.cursor =None # this is the cursor
self.connect = None # this is the cnx the mysql object
self.tables = ['server','personal_info','credentials'] # this shows how many databse table are there
self.m_database = m_database
class insert_database_values(database_creator):
def __init__(self):
database_creator.__init__(self , username , password , m_database)
簡而言之,它已經出現在評論中。 你是對的:
class insert_database_values(database_creator):
意味着您的新類insert_database_values
繼承自類database_creator
。 但是,您還用新的構造函數( __init__
)覆蓋了它的構造函數( __init__
),該構造函數不帶任何參數( self
實例除外),因此在運行時:
def __init__(self):
database_creator.__init__(self , username , password , m_database)
在此范圍內,解釋器確實不知道變量username
,...。
實際上,在這種情況下,除非您打算為insert_database_values
構造函數添加省略的更多功能,否則無需定義您自己的函數僅調用父函數,只需跳過這兩行並依靠繼承來工作為了你。 否則,您可以:
def __init__(self, username , password , m_database):
database_creator.__init__(self , username , password , m_database)
並根據需要添加其他實例初始化步驟。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.