2014-12-04 86 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 
相关问题