你可以在课堂上使用字符串吗? 对于我的计算机科学项目,我需要在我的对象中使用字符串,但我无法 为简单起见,这是一个例子:
class test:
def __init__(self,string,integer):
string = self.string
integer = self.integer
string = 'hi'
integer = 4
variable = test(string, integer)
当我运行它时,我得到一个错误,因为变量字符串是一个字符串 我的问题是,有没有办法在类
中使用字符串答案 0 :(得分:2)
你已经倒退了:
class test:
def __init__(self,string,integer):
self.string = string
self.integer = integer
string = 'hi'
integer = 4
variable = test(string, integer)
答案 1 :(得分: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)
答案 2 :(得分:1)
我让__init__
部分混淆了。它应该是:
self.string = string
不
string = self.string