我嘗試學習 Python 中的類。目前,我使用 Corey Schafer 的教程。
這是他寫的:
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first "." last '@company.com'
emp_1 = Employee('First1', 'Last1', 50000)
emp_2 = Employee('First2', 'Last2', 60000)
print(emp_1.email)
print(emp_2.email)
我的問題是:為什么他在這里也不使用self: self.email = self .first "." 自我.last '@company.com'
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = self.first "." self.last '@company.com'
emp_1 = Employee('First1', 'Last1', 50000)
emp_2 = Employee('First2', 'Last2', 60000)
print(emp_1.email)
print(emp_2.email)
兩種方式的輸出是相同的。
uj5u.com熱心網友回復:
self.first如果你使用或first在方法內部沒有區別,__init__因為它self.first也指向同一個變數,即first. 使變數成為屬性self只是使其成為實體變數并允許您在類中的任何位置訪問它
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/471693.html
