Python函数问题

2020-08-13 09:31发布

问题:

class User():
def init(self,firstname,lastname):
self.firstname=firstname
self.lastname=lastname
def describe_user(self):
print("用户名称为 "+self.lastname.title()+self.firstname)
def greet_user(self):
print("您好 "+self.lastname.title()

user_b=User('zhang','shi')
user_b.describe_user

回答1:

如果没有继承,类名后面的括号可以不写;变量名没有title()方法,init方法注意前后的两个下划线

class User():
    def __init__(self, firstname, lastname):
        self.firstname = firstname
        self.lastname = lastname
    def describe_user(self):
        print("用户名称为 "+self.lastname+self.firstname)
    def greet_user(self):
        print("您好 "+self.lastname)

user_b=User('zhang','shi')
user_b.describe_user()   # 用户名称为 shizhang



回答2:

class User():
    def __init__(self,firstname,lastname):
        self._firstname = firstname
        self._lastname = lastname

    def describe_user(self):
        print("用户名称为 ",  self._lastname, self._firstname)

    def greet_user(self):
        print("您好 ", self._lastname)

if __name__ == "__main__":
    user_b = User('zhang','shi')
    user_b.describe_user()