实例一:
import datetime
class Student:
def __init__(self,name,birthdate):
self.name = name
self.birthdate = birthdate
@property
def age(self):
return datetime.date.date.today().year - self.birthdate.year
@age.setter
def age(self,value):
raise AttributeError('禁止赋值年龄!')
@age.deleter
def age(self):
raise AttributeError('年龄不能删除!')
if __name__ == '__main__':
# 如果模块是被直接运行的,则代码块被运行,如果模块是被导入的,则代码块不被运行。
s= Student('tom',datetime.date(1992,3,1))
print(s.birthdate)
print(s.age)
实例二:
import math
class Circle:
def __init__(self,radius):
self.radius = radius
def get_area(self):
return math.pi* self.radius**2
c= Circle(4.0)
print('圆的面积是:{}'.format(c.get_area()))
实例三:
class Employee:
def __init__(self,department,name,birthdate,salary):
self.department =department
self.name =name
self.birthdate = birthdate
self.salary = salary
def __repr__(self):
return'<员工:{}>'.format(self.name)
def working(self):
print('员工:{},在工作。。'.format(self.name))
class Programer(Employee):
def __init__(self,department,name,birthdate,salary,specialty,project):
super().__init__(department,name,birthdate,salary)
#super()是用于调用父类(超类)的一个方法。
self.project=project
self.specialty = specialty
def working(self):
print('程序员:{}在开发项目:{}...'.format(self.name,self.project))