【问题标题】:Using a method class outside the class & inside the class在类外和类内使用方法类
【发布时间】:2020-05-02 14:23:48
【问题描述】:

我试图真正理解 python 中的类方法发生了什么,但遇到了以下我无法理解的内容。

我的代码:

class exampleclass():

    def __init__(self,text):
        self.text = text

        self.firstletter = text[0]

        # the method has to be run --> with ()
        self.lastletter = self.methodlast()

        # the option that I used to use:
        self.secondletter = self.method2(self.text)

        # with the variable last letter I do something else
        # The order is important. lastletter is already defined here.

    def methodlast(self):
        return self.text[-1]

    def method2(self, text):
        return text[1]

    def methodX5(self):
        # addind a variable to the class
        self.longstring = self.lastletter * 5

我的意图是通过方法创建类方法的属性,并且我还希望能够从类外部单独访问这些方法。

理想情况下我希望:

cla_ins = exampleclass("this is a text")

但我也想独立于类实例使用该方法:

second_letter  = exampleclass.method2("whatever")

使用调用类的方法不行:

try:
    a =exampleclass.method2("whatever")
    print(a)
except Exception as e: 
    print(str(e))

给出错误:

method2() missing 1 required positional argument: 'text'

使用实例有效:

try:
    a = cla_ins.method2("whatever")
    print(a)
except Exception as e: 
    print(str(e))

应该如何构建一个类以使其具有可从类内部和外部访问的方法?

我的意思是从内部:

self.secondletter = self.method2(self.text)

我的意思是在外面:

a = exampleclass.mehtod2("whatever")

看起来我只能使用类的实例调用方法类。那将使我的整个推理无效。即我使用实例的方法,或者我不使用外部的方法,对吗?

到目前为止还咨询了其他链接:

【问题讨论】:

  • 你打错了是method2而不是mehtod2

标签: python class methods


【解决方案1】:

你确定你没有打错字吗? mehtod2 != 方法2

【讨论】:

    【解决方案2】:

    我认为,您的代码中有错字。您已经创建了方法method2,但调用了方法mehtod2

    【讨论】:

      【解决方案3】:

      看起来我只能使用 类。

      确实如此。

      你可以使用@classmethod 注解来创建一个类方法。请注意,类方法不能更改实例状态(因此,您的示例中的 method2 可以通过添加注释并将签名中的 self 参数更改为 cls 来成为类方法)。

      【讨论】:

      • 对不起各位,错字已更正。问题部分独立于拼写错误
      • 您可以通过单击左侧的灰色大复选按钮来接受一个答案(如果它对您有帮助)。如果您希望可以通过单击上方灰色三角形为任何好的答案的任何作者添加 +10 分
      猜你喜欢
      • 1970-01-01
      • 2019-04-16
      • 2016-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 2012-02-21
      • 1970-01-01
      相关资源
      最近更新 更多