【发布时间】: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