qq_29443517
xstdys
采纳率66.7%
2019-05-30 18:29

python类问题,不是init两边的下划线问题

已采纳

Traceback (most recent call last):

File "C:/Users/szy/Desktop/python例子/9-3.py", line 24, in
user_1.describe_user()
TypeError: describe_user() takes no arguments (1 given)

代码:

class User(object):
    def __init__(self,first_name,last_name,age,gender):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age
        self.gender = gender

    def describe_user():
        full_name = self.first_name +self.last_name
        print("\nThe user's full name is " + full_name.title() + '.')
        print("The user is " + str(self.age) + "years old.")
        print("The user is a " + self.gender + ".")

    def greet_user():
        if self.gender == 'man':
            print("Hello, Mr " + self.first_name + '!' )
        else:
            print("Hello,Mrs " + self.first_name + '!')
        print(full_name.title())    

user1 = User('smith','tom',34,'men')
user2 = User('Elizabeth','alice',24,'women')
user1.describe_user()
user1.greet_user()
user2.describe_user()
user2.greet_user()

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • fly_goodsmile fly_goodsmile 2年前

    函数没有SELF
    class User(object):
    def init(self,first_name,last_name,age,gender):
    self.first_name = first_name
    self.last_name = last_name
    self.age = age
    self.gender = gender

    def describe_user(self):
        full_name = self.first_name +self.last_name
        print("\nThe user's full name is " + full_name.title() + '.')
        print("The user is " + str(self.age) + "years old.")
        print("The user is a " + self.gender + ".")
    
    def greet_user(self):
        if self.gender == 'man':
            print("Hello, Mr " + self.first_name + '!' )
        else:
            print("Hello,Mrs " + self.first_name + '!')
        print(full_name.title())    
    

    user1 = User('smith','tom',34,'men')
    user2 = User('Elizabeth','alice',24,'women')

    user1.describe_user()

    The user's full name is Smithtom.
    The user is 34years old.
    The user is a men.

    点赞 评论 复制链接分享