简体   繁体   English

需要帮助创建 Python 类

[英]Need help creating a Python Class

I need some help with creating a python class and method.我需要一些帮助来创建 python 类和方法。 I don't really know what I am doing wrong but I keep getting the correct answer and then this error: <__main__.stringToMerge object at 0x7f9161925fd0>我真的不知道我做错了什么,但我一直得到正确的答案,然后出现这个错误: <__main__.stringToMerge object at 0x7f9161925fd0>

I want to create an object with two string that merges them alternatively.我想用两个字符串创建一个对象,交替合并它们。 For example the object would be obj.s1="aaaaa" , obj.s2="bb" and the correct output would be: "ababaaa" .例如,对象是obj.s1="aaaaa"obj.s2="bb" ,正确的输出是: "ababaaa"

Ty in advance for any help provided :D提前提供任何帮助:D

class stringToMerge:
  def __init__(self, string1, string2):
    self.string1 = string1
    self.string2 = string2

  def SM(self, string1, string2):
    self.string1 = string1
    self.string2 = string2
    string3 = ""
    i = 0
    while i<len(string1) and i<len(string2):
      string3 = string3+string1[i]
      string3 = string3+string2[i]
      i = i+1
    while i<len(string1):
      string3 = string3+string1[i]
      i = i+1
    while i<len(string2):
      string3 = string3+string1[i]
      i = i+1  
    print(string3)


obj = stringToMerge('aaaaa', 'bb')
obj.SM(obj.string1, obj.string2)
print(obj) 

Already your code is printing the expected output.您的代码已经在打印预期的输出。 But additionally you are getting this message <__main__.stringToMerge object at 0x7f9161925fd0> because you are printing the instance of the class print(obj) .但是另外你会收到这条消息<__main__.stringToMerge object at 0x7f9161925fd0>因为你正在打印类print(obj)的实例。 Comment or remove this line you won't find this again.评论或删除此行,您将不会再找到此行。

Your main Issue was that you were not returning anything and you were trying to print the object.您的主要问题是您没有返回任何东西,而是试图打印该对象。 Hence the reason it printed out < main .stringToMerge object at 0x7f9161925fd0>.因此它打印出 < main .stringToMerge object at 0x7f9161925fd0> 的原因。 In the snippet below I edited the code to be more concise, and I added a return statement to the function.在下面的代码片段中,我将代码编辑得更简洁,并向函数添加了一个 return 语句。 Once this was done, I assigned a variable to the return value of the SM() method and printed said variable完成后,我将一个变量分配给 SM() 方法的返回值并打印该变量

class stringToMerge:
  def __init__(self, string1, string2):
    self.string1 = string1
    self.string2 = string2
  def longestString(string1,string2):
      if len(string1) < len(string2):
          return string2
      else:
          return string1
  def SM(self, string1, string2):
    string3 = ""
    i = 0
    for char1,char2 in zip(string1, string2):
        string3 += char1+char2
        i+= 1
    longestString = stringToMerge.longestString(string1,string2)
    return string3+longestString[i:]

obj = stringToMerge('aaaaa', 'bb')
final = obj.SM(obj.string1, obj.string2)
print(final)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM