I am trying to truly understand what is going on with class methods in python and came across to the following that I can not understand.
My code:
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
My intention is create attributes of the class method by method and I also want the methods to be able to individually be accessed from outside the class.
ideally I would like:
cla_ins = exampleclass("this is a text")
But I also want to use the method independently of a class instance:
second_letter = exampleclass.method2("whatever")
Using the method calling the class is not OK:
try:
a =exampleclass.method2("whatever")
print(a)
except Exception as e:
print(str(e))
gives error:
method2() missing 1 required positional argument: 'text'
Using the instance works:
try:
a = cla_ins.method2("whatever")
print(a)
except Exception as e:
print(str(e))
How should a class be built to have methods to be accessed from inside the class and also from outside?
From inside I mean:
self.secondletter = self.method2(self.text)
From outside I mean:
a = exampleclass.mehtod2("whatever")
It looks like I can only call a method class using an instance of the class. That would make my whole reasoning void. i.e. I use the method with instances or I don't use the method from outside, right?
So far other links consulted: