2014-12-04 39 views
-6

你可以在類中使用字符串嗎? 對於我的計算機科學項目,我需要在我對象使用字符串,但我無法 爲了簡單起見這裏有一個例子:你可以在類中使用字符串嗎

class test: 
    def __init__(self,string,integer): 
     string = self.string 
     integer = self.integer 

string = 'hi' 
integer = 4 
variable = test(string, integer) 

當我運行此我得到一個錯誤,因爲變量string是一個字符串 我的問題是,有沒有使用類

+0

顯示完整的錯誤;並在編輯問題時處理縮進。 – Evert 2014-12-04 16:22:36

+0

您的問題的答案是:是的。 – Evert 2014-12-04 16:23:27

+0

'integer = self.integer'你期望做什麼? (特別是因爲self.integer從來沒有定義?) – njzk2 2014-12-04 16:23:35

回答

2

串的方式你知道了倒退:

class test: 
    def __init__(self,string,integer): 
     self.string = string 
     self.integer = integer 

string = 'hi' 
integer = 4 
variable = test(string, integer) 
1

你的問題不在於字符串,它與沒有得到什麼「自我」。手段。你想要的是:

class Test(object): 
    def __init__(self, string, integer): 
     # here 'string' is the parameter variable, 
     # 'self' is the current Test instance. 
     # ATM 'self' doesn't yet have a 'self.string' 
     # attribute so we create it by assigning 'string' 
     # to 'self.string'. 
     self.string = string 
     # and from now on we can refer to this Test instance's 
     # 'string' attribute as 'self.string' from within Test methods 
     # and as 'varname.string' from the outside world. 

     # same thing here... 
     self.integer = integer 

var = Test("foo", 42) 
1

我剛把__init__部分混在一起。它應該是:

self.string = string 

不是:

string = self.string 
相關問題