一、私有化
1.訪問(wèn)權(quán)限:
公開(kāi)的(public):類(lèi)里面、類(lèi)外面都可以使用,也可以被繼承
保護(hù)的(protect):類(lèi)里面可以使用,類(lèi)外面不能使用,可以被繼承
私有的(private):類(lèi)里面可以使用,類(lèi)外面不能使用,也不能被繼承
2.python中類(lèi)的內(nèi)容的訪問(wèn)權(quán)限
嚴(yán)格來(lái)說(shuō),python類(lèi)中的內(nèi)容只有公開(kāi)的,私有化是假的私有化
3.怎么私有化
在方法名前或者屬性名前加__(但是名字后不能加__)
原理:不是真的私有化,而是在__開(kāi)頭的屬性名和方法名前加了'_類(lèi)名'
class Person:
num = 61
__num2 = 100
def __init__(self, name, age=18):
self.name = name
self.age = age
self.gender = '男'
self.__gender = '男'
def func1(self):
print('%s今年%d歲' % (self.name, self.age), self.__gender)
self.__func11()
def __func11(self):
print('私有的對(duì)象方法')
@staticmethod
def func2():
print('我是靜態(tài)方法1')
@staticmethod
def __func22():
print('我是靜態(tài)方法1')
@classmethod
def func3(cls):
print(cls.num)
print(cls.__num2)
print('==========默認(rèn)公開(kāi)的屬性和方法在類(lèi)的外面都可以用========')
print(Person.num)
p1 = Person('小明')
print(p1.name, p1.age, p1.gender)
p1.func1()
Person.func2()
print('===============私有的屬性和方法==========')
# print(Person.__num2) # AttributeError: type object 'Person' has no attribute '__num2'
Person.func3()
# print(p1.__gender) # AttributeError: 'Person' object has no attribute '__gender'
# p1.__func11() # AttributeError: 'Person' object has no attribute '__func11'
# Person.__func22() # AttributeError: type object 'Person' has no attribute '__func22'
print(p1.__dict__)
print(p1._Person__gender)
print(Person._Person__num2)
二、getter和setter
時(shí)間戳:當(dāng)前時(shí)間距離1970年1月1日0時(shí)0分0秒的時(shí)間差,單位是秒
# 獲取當(dāng)前時(shí)間的時(shí)間戳
time1 = time.time()
print(time1)
# localtime(時(shí)間戳) - 將時(shí)間戳轉(zhuǎn)換成當(dāng)?shù)氐木唧w時(shí)間
time2 = time.localtime(time1)
print(time2)
1.getter和setter
1)什么時(shí)候用
如果希望在對(duì)象屬性賦值前做點(diǎn)別的什么事情,就給這個(gè)屬性添加setter
如果希望在獲取屬性值之前做點(diǎn)別的什么事情,就給這個(gè)屬性添加getter
2)怎么用
getter
a. 將需要添加的getter的屬性名前加_
b. 聲明函數(shù):聲明前加@property;
函數(shù)名是不帶_的屬性名
函數(shù)需要一個(gè)返回值,返回值就是獲取這個(gè)屬性能夠得到的值
c. 在外面使用屬性的時(shí)候會(huì)不帶下劃線
setter:
注意:如果想要給屬性添加setter,必須先添加getter
a. 聲明函數(shù):聲明前加@getter名.setter;
函數(shù)名是不帶_的屬性名;
函數(shù)不需要返回值,但需要一個(gè)參數(shù),這個(gè)參數(shù)就是給屬性賦的值
b. 在外面給屬性賦值的時(shí)候不帶下劃線
class Person:
def __init__(self, age:int):
self._age = age
self._time = 0
@property
def time(self):
t_time = time.localtime(self._time)
return '{}-{}-{} {}:{}:{}'.format(t_time.tm_year, t_time.tm_mon, t_time.tm_mday, t_time.tm_hour, t_time.tm_min, t_time.tm_sec)
@property
def age(self):
return self._age
@age.setter
def age(self, value):
print('value:', value)
if isinstance(value, int):
if 0 <= value <= 200:
self._age = value
else:
raise ValueError
else:
raise ValueError
p1 = Person(10)
p1.age = 18
# p1.age = 'abc'
# p1.age = [1, 2, 3]
# p1.age = 19273897298
print(p1.time)
class Circle:
pi = 3.1415926
def __init__(self, r):
self.r = r
self._area = 0
@property
def area(self):
return Circle.pi * self.r * self.r
@area.setter
def area(self, value):
print('給area屬性賦值:', value)
raise ValueError
c1 = Circle(1)
print(c1.area) # 本質(zhì)是在調(diào)用area函數(shù): c1.area()
c1.r = 10
print(c1.area) # 本質(zhì)是在調(diào)用area函數(shù): c1.area()
c1.r = 3
print(c1.area) # 本質(zhì)是在調(diào)用getter的area函數(shù): c1.area()
# c1.area = 31.4 # 本質(zhì)是在調(diào)用setter的area函數(shù): c1.area(31.4)
# c1.area = 1000 # 本質(zhì)是在調(diào)用setter的area函數(shù): c1.area(1000)
三、繼承
1.什么是繼承
繼承是讓子類(lèi)直接擁有父類(lèi)的屬性和方法
子類(lèi) - 繼承者
父類(lèi) - 被繼承者,又叫超類(lèi)
2.怎么繼承
語(yǔ)法:
class 類(lèi)名(父類(lèi)1, 父類(lèi)2,...):
類(lèi)的說(shuō)明文檔
類(lèi)的內(nèi)容
3.繼承哪些東西
父類(lèi)所有的屬性和方法子類(lèi)都會(huì)繼承
class Person(object):
num = 61
def __init__(self):
self.name = '小明'
self.age = 18
@staticmethod
def func1():
print('靜態(tài)方法')
class Student(Person):
pass
# 子類(lèi)直接使用父類(lèi)的屬性和方法
print(Student.num)
Student.func1()
stu = Student()
print(stu.name, stu.age)
4.子類(lèi)中添加屬性和方法
1)添加方法和字段
在子類(lèi)直接聲明新的字段和方法;
注意:如果添加的字段名和方法名與父類(lèi)的字段名和方法名同名了,子類(lèi)中的字段和方法會(huì)覆蓋父類(lèi)的字段和方法 - 重寫(xiě)
2)添加對(duì)象屬性
在自己的init方法中添加新的屬性,并且需要通過(guò)super()去調(diào)用父類(lèi)的init方法繼承父類(lèi)的屬性
5.super的使用
可以在類(lèi)中的任何一個(gè)對(duì)象方法或者類(lèi)方法中區(qū)通過(guò)super()調(diào)用父類(lèi)的對(duì)象方法或者類(lèi)方法
super(類(lèi)1,類(lèi)1的對(duì)象)。方法() -> 調(diào)用類(lèi)1的父類(lèi)中的方法
super().方法() <==> super(當(dāng)前類(lèi),當(dāng)前類(lèi)對(duì)象)
super(type,obj) -> 要求obj必須是type的對(duì)象或者是type的子類(lèi)對(duì)象
class Animal:
num = 100
def __init__(self):
self.age = 10
self.gender = '雌'
@staticmethod
def a_func1():
print('動(dòng)物的對(duì)象方法1')
@staticmethod
def func1():
print('動(dòng)物中的靜態(tài)方法')
def func2(self):
print('動(dòng)物中的對(duì)象方法2')
@classmethod
def func4(cls):
print('動(dòng)物中的類(lèi)方法')
class Cat(Animal):
voice = '喵~'
def __init__(self):
super().__init__() # 調(diào)用當(dāng)前類(lèi)的父類(lèi)的__init__方法
self.color = '白色'
self.breed = '加菲貓'
@classmethod
def c_func1(cls):
print('貓的類(lèi)方法')
@staticmethod
def func1():
print('貓中的靜態(tài)方法')
# 注意: 靜態(tài)方法中不能直接使用super()
# super().a_func1()
def func3(self):
super().func2()
print('貓中的對(duì)象方法')
@classmethod
def func5(cls):
print('貓中的類(lèi)方法2')
super().func4()
print(Cat.num, Cat.voice)
Cat.a_func1()
Cat.c_func1()
Cat.func1() # 貓中的靜態(tài)方法
Animal.func1() # 動(dòng)物中的靜態(tài)方法
cat1 = Cat()
print(cat1.age, cat1.gender)
print(cat1.color, cat1.breed)
print('===============super================')
cat1.func3()
Cat.func5()
print('===========================================================================')
class A:
def func(self):
print('this is A')
class B(A):
def func(self):
print('this is B')
class D(A):
def func(self):
print('this is D')
class C(B):
def func(self):
# super().func()
# super(C, self).func()
# super(B, self).func()
# super(D, D()).func()
# super(A, A()).func()
print('this is C')
obj = C()
# ==> super().func()
# obj.func() # this is B; this is C
# ==> super(C, self).func()
# obj.func() # this is B; this is C
# ==> super(B, B()).func() / super(B, self).func()
# obj.func() # this is A; this is C
# ==> super(D, D()).func()
# obj.func() # this is A; this is C
# ==> super(A, A()).func()
# obj.func() # AttributeError: 'super' object has no attribute 'func'
四、多繼承
class Animal:
num = 100
def __init__(self, age=0, gender='雄'):
self.age = age
self.gender = gender
def a_func1(self):
print('動(dòng)物的對(duì)象方法')
def message(self):
print('this is Animal')
class Fly:
flag = '飛行'
def __init__(self, height=1000, time=3):
self.height = height
self.time = time
@classmethod
def f_func1(cls):
print('飛行的類(lèi)方法')
def message(self):
print('this is Fly')
class Bird(Animal, Fly):
pass
class A1:
def message(self):
super(Bird, Bird()).message()
b1 = Bird()
# 字段都可以繼承
print(Bird.num, Bird.flag)
# 方法都可以繼承
b1.a_func1()
Bird.f_func1()
# 對(duì)象屬性只能繼承第一個(gè)父類(lèi)的
print(b1.age, b1.gender)
# print(b1.height, b1.time) # AttributeError: 'Bird' object has no attribute 'height'
b1.message()
A1().message()
# 查看繼承順序: 先畫(huà)出和需要的類(lèi)相關(guān)聯(lián)的所有的父類(lèi)的繼承關(guān)系,然后從左往右看沒(méi)有子類(lèi)的類(lèi)