class Employee:
地點="south": Employee.
def describe(self)。
print(self.location)
我是否應該使用self.class_variable來訪問類方法中的類變數?
class Employee:
地點="south": Employee.
def describe(self)。
print(Employee.location)
或者說我應該使用class_name.class_variable? 哪一個才是正確的約定? 這兩者之間有什么區別嗎?
編輯1。 除了人們給出的其他答案,我發現 如果你改變self.class_variable,它將只對該實體進行改變。 而如果你改變class_name.class_variable,它將為所有當前和未來的實體改變。 希望這有幫助。
uj5u.com熱心網友回復:
如果你進行子類化,這個區別就變得很重要了:
class Employee。
位置="南"
def describe_self(self)。
print(self.location)
def describe_class(self)。
print(Employee.location)
...
class Salesman(Employee)。
位置="north"。
...
Employee().describe_self()
南方
Employee().describe_class()
南方
Salesman().describe_self()
北部
Salesman().description_class()
南邊
因為如果你使用子類,self的型別實際上可能不是Employee。
uj5u.com熱心網友回復:
是的,兩者之間是有區別的。
class Employee。
地點="south": Employee.
class EmployeeSelf(Employee)。
def __str__(self):
return self.location
class EmployeeEmployee(Employee)。
def __str__(self):
return Employee.location
emp = EmployeeSelf()
emp.location = 'north'print(emp)
emp0=EmployeeEmployee()
emp0.location = 'north' 'north'
print(emp0)
看一下這個例子。當識別符號self指向物件本身時,Employee識別符號指向類。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/310702.html
標籤:
