面向对象的特征:
封装
继承 提高代码重用
多态
class Book:
def __init__(self,title,price,author): //赋默认值的参数需在最后
self.title = title
self.price = price
self.author = author
if __name__=='__main__':
book = Book('Python经典',price=29.0,author='Tom')
实体化后调用时显示有意义信息的方法:
def __repr__(self):
return '<图书:{} at ox{}>'.format(self.title,id(self))
打印时:(若不用该函数,则与__repr__(self)代替)
def __str__(self):
return'[图书:{},定价:{}]'.format(self.title, self.price)
统计图书的个数 -- 全局 -- 和实例无关的东西不要写到init中,不加self
class Book:
count = 0
def __init__(self,title,price,author): //赋默认值的参数需在最后
self.title = title
self.price = price
self.author = author
Book.count+=1
def__del__(self):
Book.count -=1
//未绑定方法
def cls_method (cls):
priny(‘类函数’)
@staticmethod (//若加上可以通过实例调用,最好不要加)
def static_method():
print('静态函数,逻辑上与实例无关')
if __name__=='__main__':
book = Book('Python经典',price=29.0,author='Tom')
del(book3)
print('图书数量:{}.format(Book.count)') //此处count也可以通过实例名调用:book.count,但不建议,可自己改掉
Book.cls_method(book)
Book.static_method()
import datetime
class Student:
def__init__(self,name,birthdate):
self.name = name
self.birthdate = birthdate
方法1:
@property //属性,装饰器
def age(self):
return datetime.date.today().year - self.birthdate.year
@age.setter
def age(self,value):
raise AttributeError('禁止赋值年龄!')
@age.deleter
def age(self):
raise AttributeError('禁止删除年龄!')
方法2:定义函数
def get_age(self):
return datetime.date.today().year - self.birthdate.year
if __name__=='__main__':
s = Student('Tom', datetime.date (1992.3.1))
print(s.birthdate)
print(s.get_age( ))
print(s.age)