-1
class Main():
    def __init__(self):
        def placeName(self):
            place_name = raw_input("\n=> Enter a place name: ")
            placename_data = place_name.strip()
            if re.match("^[a-zA-Z]*$", placename_data):
                return placename_data
            else:
                print("Error! Only Alphabets from are allowed as input!")
a = Main()
new = a.placeName()

Above code for placeName() method runs correctly without using class but when I try to add it in a class, code gives an attribute error . Can't understand what is wrong here.

R.N.
  • 3
  • 1
  • 3
    If you want to define a method in your `Main` class, don't define it _inside_ `__init__`. For this example, you can remove `def __init__(self):` entirely. – khelwood Mar 21 '17 at 13:11
  • @Khelwood: After removing init I am getting this error – R.N. Mar 21 '17 at 13:21
  • That's a different error produced by something not shown in the code you have posted here. – khelwood Mar 21 '17 at 15:18

1 Answers1

1

You don't need to define __init__ inside the Main class.

class Main():
    def placeName(self):
        place_name = raw_input("\n=> Enter a place name: ")
        placename_data = place_name.strip()
        if re.match("^[a-zA-Z]*$", placename_data):
            return placename_data
        else:
            print("Error! Only Alphabets from are allowed as input!")
a = Main()
new = a.placeName()

Please remove __init__ method and try.

khelwood
  • 55,782
  • 14
  • 81
  • 108
Karthikeyan KR
  • 1,134
  • 1
  • 17
  • 38
  • class Main(): def placeName(): place_name = raw_input("\n=> Enter a place name: ") print(place_name) a = Main() b = a.placeName() – R.N. Mar 21 '17 at 13:23
  • Sorry I tried removing init and also tried with simplest code but it comes a type error – R.N. Mar 21 '17 at 13:25
  • you forgot 'self' in function – Karthikeyan KR Mar 21 '17 at 13:26
  • Hey! Thanks, it works now. Sorry I am a beginner to classes. I have a question, why did we required self here? I had the understanding of using it in init method only. – R.N. Mar 21 '17 at 13:35
  • In python for every method within a class required self, you can refer it here http://stackoverflow.com/questions/2709821/what-is-the-purpose-of-self – Karthikeyan KR Mar 21 '17 at 13:38
  • Brilliant! Thanks for the help :) – R.N. Mar 21 '17 at 13:52