#1.初始化實例化屬性。
#可接受任意關鍵字參數,並把他們都作為屬性賦值給實例。使用**kw,除了可以直接使用self.name = 'xxx'設置一個屬性外,還可以通過setattr(self, 'name', 'xxx')設置屬性。
class Person(object):
def __init__(self, name, gender, **kw):
self.name = name
self.gender = gender
for k,v in kw.items():
setattr(self, k, v)
xiaoming = Person('Xiao Ming', 'Male', birth='1990-1-1', job='Student')
print(xiaoming.name)
print(xiaoming.job)
#2.類中的私有成員,雙下划線開頭的"__score"不能直接被外部訪問。
class Person1(object):
def __init__(self, name, score):
self.name = name
self._gender = 'Male'
self.__score = score
p1 = Person1('Bob', 59)
try:
print(p1.__score) #AttributeError: 'Person1' object has no attribute '__score'
except AttributeError:
print('attrbuteerror')
#3.創建類屬性。實例屬性每個實例都各自擁有,互相獨立,而類屬性有且只有一份。
class Person2(object):
address = 'Earth'
def __init__(self, name):
self.name = name
print(Person2.address)
p2 = Person2('Tom')
print(Person2.address)
#請給Person3類添加一個類屬性count每創建一個實例count屬性就加1這樣就可以統計出一共創建了多少個Person3的實例。
class Person3(object):
count = 0
def __init__(self, name):
self.name = name
Person3.count += 1
p3 = Person3('Alice')
print(p3.count)
p3_1 = Person3('Tim')
print(p3_1.count)
#4.python中類屬性和實例屬性名字沖突怎么辦?
#請把上節的Person3類屬性count改為__count,再試試能否從實例和類訪問該屬性。
class Person4(object):
__count = 0
def __init__(self, name):
self.name = name
Person4.__count += 1
print(Person4.__count)
p4 = Person4('Bob')
p4_1 = Person4('Alice')
try:
print(Person4.__count) #AttributeError: type object 'Person4' has no attribute '__count'
except AttributeError:
print('AttributeError')
##類屬性的公開和私有,如果沒有雙下划線,外部可以調用,如果有,只能在類內部使用。
#5.一個實例的私有屬性就是以__開頭的屬性,無法被外部訪問,那這些屬性定義有什么用?
#雖然私有屬性無法從外部訪問,但是,從類的內部是可以訪問的。除了可以定義實例的屬性外,還可以定義實例的方法。
#實例的方法就是在類中定義的函數,它的第一個參數永遠是self,指向調用該方法的實例本身,其他參數和一個普通函數是完全一樣的:
class Person5(object):
def __init__(self, name):
self.__name = name
def get_name(self):
return self.__name
p5 = Person5('Bob')
print(p5.get_name())
#任務:請給Person5類增加一個私有屬性__score,表示分數,再增加一個實例方法get_grade(),
#能根據__score的值分別返回A-優秀, B-及格, C-不及格三檔。
class Person6(object):
def __init__(self, name, score):
self.name = name
self.__score = score
def get_grade(self):
if self.__score >= 80:
return "A-Excellent"
elif self.__score >= 60:
return "B-Passed"
return "C-Failed"
p6_1 = Person6('Bob', 89)
p6_2 = Person6('Alice', 69)
p6_3 = Person6('Tim', 59)
print(p6_1.get_grade())
print(p6_2.get_grade())
print(p6_3.get_grade())
#6.python中方法也是屬性,由於屬性可以是普通的值對象,如str,int等,也可以是方法,還可以是函數,大家看看下面代碼的運行結果,請想一想p6.get_grade為什么是函數而不是方法:
class Person6(object):
def __init__(self, name, score):
self.name = name
self.score = score
self.get_grade = lambda: 'A'
p6 = Person6('Bob', 90)
print(p6.get_grade) #<function Person6.__init__.<locals>.<lambda> at 0x000001D1244300D0>
print(p6.get_grade()) #A
#直接把lambda函數賦值給self.get_grade和綁定方法有所不同,函數調用不需要傳入self,但是方法調用需要傳入self。
#p6.get_grade是屬性,只不過這里的屬性是一個函數對象.
#p6.get_grade()是方法,前面的p6就是調用這個方法的對象,即實例,整句來說就是實例方法