1.析构函数和析构方法
class People(object):
def __init__(self, name, age):
self.name = name
self.age = age
print("创建对象成功.......")
def __del__(self):
print("删除对象成功.......")
if __name__ == '__main__':
p1 = People('fentiao', 12)
2.对象str与repr方法
class People(object):
def __init__(self, name, age):
self.name = name
self.age = age
print("创建对象成功.......")
def __del__(self):
print("删除对象成功.......")
def __str__(self):
return 'People(%s, %d)' %(self.name, self.age)
def __repr__(self):
return "People(%s)" %(self.name)
def __hello(self):
print("hello")
def world(self):
self.__hello()
if __name__ == '__main__':
p1 = People('fentiao', 12)
print(p1)
print(p1.__str__())
p1.world()
print(str(p1))
print(repr(p1))
print("name:%s, age:%d, scores:%s" % ('westos', 10, dict(a=1, b=2)))
print("name:%s, age:%d, scores:%s" % ('westos', 10, (1, 2)))
print("name:%s, age:%d, name:%s" % ('westos', 10, 'westos'))
print("name:{0}, age:{1}, scores:{2}".format('westos', 10, [100, 100, 100]))
print("name:{0}, age:{1}, scores:{0}".format('westos', 10))
print("name:{0}, id:{1:.3f}, scores:{0}".format('westos', 19.2332435))
d = {'max': 100, 'min': 10}
print("MAX: {max}, MIN:{min}".format(max=100, min=10))
print("MAX: {max}, MIN:{min}".format(**d))
point = (3,4)
print("x:{0[0]}, y:{0[1]}".format(point))
class Book(object):
def __init__(self, name, author, state, bookIndex):
self.name = name
self.author = author
self.state = state
self.bookIndex = bookIndex
def __str__(self):
return 'Book(%s, %d)' %(self.name, self.state)
b = Book('python', 'guido', 1, 'IND444')
print("name:{b.name}, state:{b.state}, author:{b.state}".format(b=b))
print("name:{0.name}, state:{0.state}, author:{0.state}".format(b))
formats = {
'ymd':"{d.year}-{d.month}-{d.day}",
'mdy':"{d.month}/{d.day}/{d.year}",
}
class Date(object):
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def __format__(self, format_spec=None):
if not format_spec:
format_spec = 'ymd'
fmt = formats[format_spec]
return fmt.format(d=self)
d = Date(2019, 8, 25)
print(format(d))
print(format(d, 'mdy'))
5.类内部装饰器
class Book(object):
def __init__(self, name, author, state, bookIndex):
self.name = name
self.author = author
self.__state = state
self.bookIndex = bookIndex
@property
def state(self):
if self.__state == 0:
return '已借出'
elif self.__state == 1:
return '未借出'
else:
return "状态异常"
@state.setter
def state(self, value):
if value in (0,1):
self.__state = value
@state.deleter
def state(self):
print("is deleteing......")
def __str__(self):
return 'Book(%s, %d)' %(self.name, self.__state)
b = Book('python', 'guido', 1, 'chddf')
print(b.state)
b.state = 0
print(b.state)
del b.state
6.实现:类的切片和索引
class Student(object):
def __init__(self, name, scores):
self.name = name
self.scores = scores
def __getitem__(self, index):
return self.scores[index]
def __setitem__(self, index, value):
self.scores[index] = value
def __delitem__(self, index):
del self.scores[index]
def hello(self):
return "hello"
s = Student('westos', [101, 100, 100])
print(s.__dict__)
7.重复与连接与成员操作符的实现
class Student(object):
def __init__(self, name, scores):
self.name = name
self.scores = scores
self.power = 100
def __add__(self, other):
self.power = self.power + other.power
return self
def __mul__(self, other):
return self.power * other
def __contains__(self, item):
return item in self.scores
def __iter__(self):
"""
iter([1,2,3,4,5])
<list_iterator object at 0x7f6e1f51ffd0>
iter({1,2,3,4,5})
<set_iterator object at 0x7f6e1f567318>
"""
return iter(self.scores)
def __repr__(self):
return "Student:%s,%s" %(self.name, self.power)
s1 = Student('westos1', [101,100,100])
s2 = Student('westos2', [100,100,100])
s3 = Student('westos3', [100,100,100])
print(s1 + s2 + s3)
8.call方法
class Student(object):
def __init__(self, name, scores, power):
self.name = name
self.scores = scores
self.power = power
def __call__(self, *args, **kwargs):
return "对象被调用......"
def __new__(cls, *args, **kwargs):
if not hasattr(cls, 'obj'):
cls.obj = object.__new__(cls)
return cls.obj
s1 = Student('westos1', [101,100,100], 100)
s2 = Student('westos1', [101,100,100], 100)
print(s1)
print(s2)