Python:TypeError:此构造函数不带参数

时间:2014-11-19 13:01:14

标签: python class email arguments

当用户输入电子邮件地址时,程序会读取电子邮件并根据其标准显示(例如yeo.myy@edu.co),如标准:

  • usernameyeo.myy
  • domainedu.co

我知道它与"@"有关。

这是代码

class Email:
    def __int__(self,emailAddr):
        self.emailAddr = emailAddr


    def domain(self):
        index = 0
        for i in range(len(emailAddr)):
            if emailAddr[i] == "@":
                index = i
            return self.emailAddr[index+1:]

    def username(self):
        index = 0
        for i in range(len(emailAddr)):
            if emailAddr[i] == "@" :
                index = i
            return self.emailAddr[:index]

def main():

    emailAddr = raw_input("Enter your email>>")

    user = Email(emailAddr)

    print "Username = ", user.username()
    print "Domain = ", user.domain()

main()

这是我得到的错误:

Traceback (most recent call last):
  File "C:/Users/Owner/Desktop/sdsd", line 29, in <module>
    main()
  File "C:/Users/Owner/Desktop/sdsd", line 24, in main
    user = Email(emailAddr)
TypeError: this constructor takes no arguments

3 个答案:

答案 0 :(得分:7)

def __int__(self,emailAddr):

您的意思是__init__吗?

def __init__(self,emailAddr):

您的方法中也遗漏了几个self,并且您的return内容不正确缩进。

def domain(self):
    index = 0
    for i in range(len(self.emailAddr)):
        if self.emailAddr[i] == "@":
            index = i
            return self.emailAddr[index+1:]

def username(self):
    index = 0
    for i in range(len(self.emailAddr)):
        if self.emailAddr[i] == "@" :
            index = i
            return self.emailAddr[:index]

结果:

Username =  yeo.myy
Domain =  edu.co

顺便提一下,我建议partitionrpartition将字符串拆分为给定分隔符上的两个部分。当然可以手动跟踪指数。

def domain(self):
    return self.emailAddr.rpartition("@")[2]
def username(self):
    return self.emailAddr.rpartition("@")[0]

答案 1 :(得分:0)

如果在初始化前后输入带有单个下划线的def _init_而不是带有两个下划线的def __init__,则可能会发生此错误。

答案 2 :(得分:-1)

class Employee:
    def __init__(self,Name,Age,Salary,Gender):
         self.Name = Name
         self.Age = Age
         self.Salary= Salary
         self.Gender = Gender
         
    def show_employee_deatils(self):
         print("Name of the employee is ",self.Name)
         print("Age of the employee is ",self.age)
         print("Salary of the employee is ",self.salary)
         print("gender of the employee is ",self.gender)
e1 = Employee('Shubham',25,25000,'male')
e1. show_Employee_deatils( )