【问题标题】:Can you use strings in classes [closed]你可以在类中使用字符串吗[关闭]
【发布时间】:2023-04-04 15:46:01
【问题描述】:

你可以在类中使用字符串吗? 对于我的计算机科学项目,我需要在我的对象中使用字符串,但我无法 为简单起见,这里举个例子:

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

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

当我运行这个时,我得到一个错误,因为变量字符串是一个字符串 我的问题是,有没有办法在类中使用字符串

【问题讨论】:

  • 显示完整错误;并在编辑问题时注意缩进。
  • 你的问题的答案是:是的。
  • integer = self.integer 你希望它做什么? (特别是因为 self.integer 从未定义?)

标签: python string class object


【解决方案1】:

我只是把__init__ 部分弄混了。应该是:

self.string = string 

不是:

string = self.string

【讨论】:

    【解决方案2】:

    您的问题不在于字符串,而在于没有得到“自我”。方法。你想要的是:

    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)
    

    【讨论】:

      【解决方案3】:

      你搞错了:

      class test:
          def __init__(self,string,integer):
              self.string = string
              self.integer = integer
      
      string = 'hi'
      integer = 4
      variable = test(string, integer)
      

      【讨论】:

        猜你喜欢
        • 2013-11-07
        • 1970-01-01
        • 2010-10-07
        • 1970-01-01
        • 2012-06-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多