目录
切片: __getslice 和 __setslice__ 和__delslice__
类属性property
作用:
property可以定义一个方法名为私有属性的名字, 让用户可以访问, 但不能修改, 保护数据的
安全性;
@属性名.setter在给属性赋值时, 先做判断;
@属性名.deleter使用内置del删除属性时,自动执行的内容
#!/usr/bin/env python
# coding:utf-8
class Student(object):
def __init__(self, name, age, score):
self.name = name
self.__age = age
self.__score = score
@property
def age(self):
return self.__age
@age.setter
def age(self, value):
if isinstance(value, int) and 0 < value <= 150:
self.__age = value
print "age update ok."
else:
self.__age = 0
print "invalid age value"
@age.deleter
def age(self):
print "you are performing the delete operation"
student1 = Student("fentiao", 10, 100)
print student1.age
student1.age = 18
print student1.age
del student1.age
实现上述效果的第二种方式:
property(fget, fset, fdel, fdoc) 定义get del doc 函数
class Student(object):
def __init__(self, name, age, score):
self.name = name
self.__age = age
self.__score = score
def get_age(self):
return self.__age
def set_age(self, value):
if isinstance(value, int) and 0 < value <= 150:
self.__age = value
print "age update ok."
else:
self.__age = 0
print "invalid age value"
def del_age(self):
print "you are performing the delete operation"
age = property(get_age, set_age, del_age, "age sttribute") ##将age 属性分配给对应的函数
class MathStudent(Student):
pass
student1 = Student("fentiao", 10, 100)
print student1.age
student1.age = 18
print student1.age
del student1.age
property应用:
信息分页显示
主机信息有很多, 为了美观, 分页显示;
当用户选择第n页,以每页多少行信息显示
将start, end返回给后端, 将需要的数据响应给前端;
hostinfo = ['172.25.254.'+str(i) for i in range(1,101)] ##生成浏览信息
class Pager(object):
def __init__(self,current_page,per_items):
self.__current_page = current_page ##当前页
self.__per_items =per_items ##每页显示多少行
@property
def start(self): ##定义当前页的起始行
val = (self.__current_page-1)*self.__per_items
return val
@property
def end(self): ##定义当前页的结束行
val = (self.__current_page)*self.__per_items
return val
p = Pager(2,5) ##实例化对象 (第几页,以每页多少行信息显示)
# p.start()
# p.end()
# print hostinfo[p.start():p.end()]
print hostinfo[p.start:p.end] #执行方式相当于前三行一起执行的效果
访问限制:
私有成员和共有成员
私有属性/方法: 类内部可以访问, 对象不能访问; 子类不能访问, 子类的对象不能访问;
共有属性/方法: 私有属性可以访问和不可以访问的, 都可以访问;
class Student(object):
def __init__(self,name,score):
self.name = name
self.__score = score
# #在类里面,双下划线开头的属性。只在类里面生效外部调用不生效
# #python将self.__属性 转换为self._类__属性,所以需要使用后者进行调用
def __judge(self):
if 90<=self.__score<=100:
print "A"
elif 80<=self.__score<90:
print "B"
else:
print "C"
class MathStudent(Student):
def getscore(self):
print self._Student__score
student1= Student("jeny",100)
# print student1.name
# #私有属性不能访问,需要通过下列方法实现
print student1._Student__score
student1._Student__judge()
#私有方法的调用
student2=MathStudent("Danny",98)
print student2.name
student2.getscore()
student2._Student__judge()
改变类的字符串显示 __str__ 和 __repr__
__str__ : 当打印对象时自动调用;
__repr__ : 当在交互式环境中, 直接输入对象时, 自动调用;
如果 __str__ 没有定义时, 那么打印对象自动调用 __repr__ ;
功能: 简化脚本测试和调试时的实例输出
class Student(object):
def __init__(self,name,sid):
self.__name = name
self.__sid =sid
def __str__(self):
return "Student(%s)" %(self.__name)
##在交互式环境中使用
def __repr__(self):
return "<%s %s>" %(self.__name,self.__sid)
if __name__ == "__main__":
s = Student("westos",001)
print s
执行脚本时:
在交互式环境中:
自定义字符串格式:
__format__
_formats={
'ymd':'{d.year}-{d.month}-{d.day}',
'mdy':'{d.month}/{d.day}/{d.year}',
'dmy':'{d.day}/{d.month}/{d.year}'
}
class Date(object):
def __init__(self,year,month,day):
self.year =year
self.month = month
self.day = day
def __format__(self,code):
if code=='':
code ='ymd'
fmt =_formats[code]
return fmt.format(d = self)
d = Date(2018,1,9)
print format(d)
print format(d,'dmy')
print format(d,'mdy')
class Student(object):
country ="China"
def __init__(self,name,age):
self.name=name
self.__age =age
def get_age(self):
return self.__age
def __getitem__(self, item):
"""
当访问某个属性时,自动执行的魔术方法
"""
return None
def __setitem__(self, key, value):
"""
当给某个属性赋值时,自动调用的魔术方法
"""
self.__dict__[key] = value
print self.__dict__[key]
print "setitem ok"
def __delitem__(self, key):
"""
当删除某个属性时,自动执行的方法
:param key:
:return:
"""
del self.__dict__[key]
print "delete ok"
s = Student('westos',10)
print s.__dict__
# s['name']
# name =s['name']
s['name']='redhat'
s['name']
del s['name']
切片: __getslice 和 __setslice__ 和__delslice__
class Student(object):
country = "china"
def __init__(self,name,age):
self.name =name
self.__age =age
def __getslice__(self,i,j):
print "__getslice__",i,j
def __setslice__(self, i, j, sequence):
print "__setslice__",i,j,sequence
def __delslice__(self, i, j):
print "__delslice__",i,j
s = Student("westos",12)
s[0:3]
s[0:3]=[12,23,45]
del s[0:3]
s[0:4]
类支持比较操作(<, <=, ==, !=, >, >=)
class Room(object):
def __init__(self,name,length,width):
self.name=name
self.length=length
self.width = width
self.square=self.length * self.width
class House(object):
def __init__(self,name,style):
self.name=name
self.style=style
self.rooms=list()
def __str__(self):
return "%s %s %s" %(self.name,self.style,self.rooms)
@property
def all_square(self):
return sum([i.square for i in self.rooms])
def __eq__(self,other):
return self.all_square == other.all_square
def __nq__(self,other):
return self.all_square != other.all_square
def __lt__(self,other):
return self.all_square < other.all_square
def __le__(self, other):
return self.all_square <= other.all_square
def __gt__(self, other):
return self.all_square > other.all_square
def __ge__(self, other):
return self.all_square >= other.all_square
def add_room(self,room):
self.rooms.append(room)
h1 = House("house1","style1")
h2 = House("house2","style2")
room1 = Room("room1",1,1)
room2 = Room("room2",2,2)
room3 = Room("room3",3,3)
print h1 == h2
print h1 > h2
输出:
迭代 __iter__
class Student(object):
def __init__(self,name):
self.name =name
self.scores = [99,88,77]
def add_score(self,score):
self.scores.append(score)
def __iter__(self):
##生成一个可迭代对象
return iter(self.scores)
s = Student("mingming")
s.add_score(66)
print s.scores
from collections import Iterable
print isinstance(s,Iterable)
for i in s:
print i
输出:
元类('type')
在python中,一切皆对象; Linux下一切皆文件;In [21]:
# Student 是个类, 实质上是个对象
# Student 类是 type 类的一个实例化