2017-02-12 82 views
-1

我練OOP概念在Python,和我過這個問題來了:保存屬性的對象在Python

class User: 
    def __init__(self, username, email, password, 
     firstname, lastname, phone): 

     self.username = "" 
     self.email = "" 
     self.password = "" 
     self.firstname = "" 
     self.lastname = "" 
     self.phone = "" 

user=User('x','y','z','f','v','c') 
print(vars(user)) 

結果:

{'username': '', 'firstname': '', 'lastname': '', 'phone': '', 'password': '', 'email': ''} 

的值不會被保存到對象。我怎樣才能解決這個問題?

回答

3

您需要將函數參數分配給實例變量。

class User: 
    def __init__(self, username, email, password, 
     firstname, lastname, phone): 

     self.username = username 
     self.email = email 
     self.password = password 
     self.firstname = firstname 
     self.lastname = lastname 
     self.phone = phone 

user=User('x','y','z','f','v','c') 
print(vars(user)) 
1

保存構造函數的參數,以適當的實例變量:

def __init__(self, username, email, password, firstname, lastname, phone): 
    self.username = username 
    # etc. 
相關問題