使用python創建一個User類


創建一個名為User的類,其中包含屬性 first_name 和 last_name 還有用戶簡介通常會設置的其他幾個屬性。在類User中定義一個名為 describe_user() 的方法,它打印用戶信息摘要;再定義一個名為 greet_user() 的方法,他向用戶發送個性化的問候。
創建多個表示不同用戶的實例,並對每個實例都調用上述兩個方法。
1、定義User類與其中的方法

 

class User():
    """創建用戶個人信息"""

    def __init__(self, first_name, last_name, phone_number = '', email = '', **user_info):
        # 在這其中我們加入了題目所要求的兩種屬性,而且還有一般網站都會要求的電話號碼與郵箱,我們最后加入了一個字典,可以讓用戶個性化的定制自己的資料
        self.name = first_name +" " + last_name
        self.phonenumber = phone_number
        self.email = email
        self.other = user_info    # 新建一個字典來接收user_info字典

    def describe_user(self):      #打印用戶信息摘要的方法
        print("This user‘ name is  " + self.name)
        print("This user's phone number is " + self.phonenumber)
        print("This user's email is " + self.email)
        print("There are any other imformations below:")
        print(self.other)

    def greet_user(self):            #向用戶發送我們的問候
        print("Hello, " + self.name)

2、新建User()的實例

AE = User('Albert','Einstein', '123456789', '88888888@qq.com', Major = 'Computer', job = 'physicist' )
AE.describe_user()
AE.greet_user()

我們在這里新建了一個AE的實例,我們輸入了其他的信息,例如他的電話號碼,郵箱,還有他自己想輸入的信息,其他的實例也可以這樣操作。
運行 describe_user() 和 greet_user() 后可以看到如下內容

This user is Albert Einstein
This user's phone number is 123456789
This user's email is 88888888@qq.com
There are any other imformations below:
{'Major': 'Computer', 'job': 'physicist'}
Hello, Albert Einstein

 

 


————————————————
版權聲明:本文為CSDN博主「21savager」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/programmerdiss/article/details/105405066


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM