西门吹雪小胖墩被生日趴和“巅峰对决”搞得既兴奋又紧张,跑来问既然python这么强大,能不能模拟他单挑“叶孤城”,最好能对比赛结果做个预测啥的。
这个...
可以是可以,但小胖墩想看的是跟他打游戏那么有画面感的模拟,
而小拍我功力还尚浅,做不到如此逼真更不用说准确预测。小胖墩很失望,看那表情我在他的鄙视链上的位置又下移了一层。
他走后我辗转难眠,懊恼用程序模拟小胖墩跟人单挑这个咋就没有现成的模块可以调用泥?!
现成的模块好像调好的模版,引入进来用自己的参数进行下个性化设置就可以了,使用起来灰常方便,帮我们实现很多我们自己根本不可能实现的操作。
而且它把数据和逻辑实现都封装起来,使得作为使用者的我们无需费劲去了解内部细节,直接拿来主义。
那帮我们实现各种功能的那些模块里面究竟是啥泥?
扒开看看会发现里面就是定义好的各种类,使用时这些类(模版)定制化地为我们生成具体的实例。
以前看面向对象编程的概念,印象最深刻的一句就是:面向对象的编程为了更贴近现实而引入的概念和方法,我试着理解理解这句话:
在现实生活中,一般从两个角度来描述事物:特征和能力。就好比你想跟小狗狗愉(帮)快(你)玩(干)耍(活),你得先了解狗?
狗:
特征:名字、身高、体重、爱吃啥...
能力:能跑、能叫、能刨地、贼能吃...
编程也一样,先用类来抽象事物,然后更好滴才为我所用。在类的定义里,特征就用属性来表达,而能力则用方法函数来描述。
类是模版,对象是模版出来的实例,比如用类表达狗,而你家的那个小泰迪旺财就是狗这个类的一个实例:
更详细的分析见“类和对象的基础知识“的视频(为什么要引入类和对象,类和对象的定义和使用,类的属性vs对象的属性)
小泰迪会跑会跳会叫(能力),在类里用方法函数来表达。
然后类还可以继承,比如我们干脆定义一个专门的类来描述泰迪狗,泰迪狗类可以继承狗类(父类)所有的属性和方法函数,亦可以定义自己这个子类独有的特征表达。
你家的泰迪旺财是泰迪类的一个实例,同时归位到狗类(父类)也没问题,所以isinstance('旺财‘,'狗类‘)才为True
”方法函数和继承“详解(方法函数:对象的方法函数,整个类的方法函数,静态函数。感觉类的继承省了不少的事儿):
类的属性不是你想改,想改就能改,万一你乱改一气咋办?也就是我们对类属性的读取和写入都要做控制,防止写入不好的数据和输出可读性更好的数据。
“类的属性没有看起来那么简单”(在类内部的隐藏变量和@property装饰器的共同努力下,我们对类的属性进行了全方位的控制):
# class Employee(object):
# pass
#
# employee1 = Employee()
# employee1.first = 'Harry'
# employee1.surname = 'Potter'
# employee1.salary = 4000
# employee1.email = This email address is being protected from spambots. You need JavaScript enabled to view it.'
# print('{}, {}, {}'.format(employee1.first + ' ' +employee1.surname,
# employee1.salary, employee1.email))
#
# employee2 = Employee()
# employee2.first = 'Bilbo'
# employee2.surname = 'Baggins'
# employee2.salary = 6000
# employee2.email = This email address is being protected from spambots. You need JavaScript enabled to view it.'
# print('{}, {}, {}'.format(employee2.first + ' ' +employee2.surname,
# employee2.salary, employee2.email))
class Employee():
raiseAmount = 1.04
employeeNum = 0
def __init__(self, first, surname, salary):
self.first = first
self.surname = surname
self.salary = salary
self.email = first + '.' + surname + This email address is being protected from spambots. You need JavaScript enabled to view it.'
Employee.employeeNum += 1
def infoSummary(self):
return '{}, {}, {}'.format(self.first + ' ' + self.surname,
self.salary, self.email)
def raiseSalary(self):
self.salary = self.salary * self.raiseAmount
employee1 = Employee('Harry', 'Potter', 4000)
employee2 = Employee('Bilbo', 'Baggins', 6000)
employee3 = Employee('Mark', 'Twain', 8000)
employee4 = Employee('Julius', 'Caesar', 12000)
print(employee2.infoSummary())
employee2.raiseAmount = 1.08
employee2.raiseSalary()
print(employee2.infoSummary())
# print(employee2.__dict__)
# print(employee1.__dict__)
# print(employee1.raiseAmount)
# print(Employee.__dict__)
print('there is {} employees'.format(Employee.employeeNum))
# class method, static method and inheritance
class Employee(object):
raiseAmount = 1.04
employeeNum = 0
def __init__(self, first, surname, salary):
self.first = first
self.surname = surname
self.salary = salary
self.email = first + '.' + surname + This email address is being protected from spambots. You need JavaScript enabled to view it.'
Employee.employeeNum += 1
def infoSummary(self):
return '{}, {}, {}'.format(self.first + ' ' + self.surname,
self.salary, self.email)
def raiseSalary(self):
self.salary = self.salary * self.raiseAmount
@classmethod
def setRaiseAmount(cls, amount):
cls.raiseAmount = amount
@classmethod
def newFromString(cls, empstr):
first, surname, salary = empstr.split('-')
return cls(first, surname, salary)
@staticmethod
def whatDay(day):
num = day.weekday()
if num == 0:
print('\nLet\'s look at the bright side. At least Mondays only happen once a week')
if num == 1:
print('\nThank goodness Monday is gone. Happy Tuesday!')
if num == 2:
print('\nIt’s Wednesday. That means that we are over the hump!')
if num == 3:
print('\nHappy Thursday! P.S. It’s almost Friday!')
if num == 4:
print('\nHello Friday, where have you been all week?')
if num == 5:
print('\nSaturday is the perfect day for a wonderful adventure')
if num == 6:
print('\nOn this lovely Sunday...')
class Writer(Employee):
raiseAmount = 1.08
def __init__(self, first, surname, salary, masterwork):
Employee.__init__(self, first, surname, salary)
self.masterwork = masterwork
def infoSummary(self):
return '{}, {}, \n{}, \n{}\n'.format(self.first + ' ' + self.surname,
self.salary, self.email, self.masterwork)
@classmethod
def newFromString(cls, empstr):
first, surname, salary, masterwork = empstr.split('-')
return cls(first, surname, salary, masterwork)
class Leader(Employee):
def __init__(self, first, surname, salary, employees=None):
super().__init__(first, surname, salary)
if employees is None:
self.employees = []
else:
self.employees = employees
def infoSummary(self):
nameList = []
for e in self.employees:
nameList.append(e.first + ' ' + e.surname)
return '{}, {}, \n{}, \n{}\n'.format(self.first + ' ' + self.surname,
self.salary, self.email, nameList)
def addEmp(self, emp):
if emp not in self.employees:
self.employees.append(emp)
def delEmp(self, emp):
if emp in self.employees:
self.employees.remove(emp)
@classmethod
def newFromString(cls, empstr):
print('\nSorry, it does not work for Leader\n')
empCharacter1 = Employee('Harry', 'Potter', 4000)
empCharacter2 = Employee('Bilbo', 'Baggins', 6000)
empWriter1 = Writer('Mark', 'Twain', 8000, 'The adventure of Tom Sawyer')
empLeader = Leader('Julius', 'Caesar', 12000, [empCharacter1, empCharacter2])
empStr1 = 'J.K-Rowling-10000-Harry Potter'
empStr2 = 'J.R.R-Tolkien-8000-The lord of rings'
empWriter2 = Writer.newFromString(empStr1)
empWriter3 = Writer.newFromString(empStr2)
# Property
class Employee(object):
raiseAmount = 1.04
employeeNum = 0
def __init__(self, first='Unknown', surname='Unknown', salary=0):
self.__first = first
self.__surname = surname
self.__salary = salary
Employee.employeeNum += 1
@property
def email(self):
return self.__first + '.' + self.__surname + This email address is being protected from spambots. You need JavaScript enabled to view it.'
@property
def fullname(self):
return self.__first + ' ' + self.__surname
@fullname.setter
def fullname(self, value):
if isinstance(value, str):
self.__first, self.__surname = value.split()
@property
def first(self):
return self.__first
@first.setter
def first(self, value):
if isinstance(value, str):
self.__first = value
else:
print('Firstname must be string')
@property
def surname(self):
return self.__surname
@surname.setter
def surname(self, value):
if isinstance(value, str):
self.__surname = value
else:
print('Surnamename must be string')
@property
def salary(self):
return self.__salary
@salary.setter
def salary(self, amount):
if isinstance(amount, int) or isinstance(amount, float):
self.__salary = amount
else:
print('Salary must be interger or float')
def infoSummary(self):
return '{}, {}, {}'.format(self.fullname,
self.salary, self.email)
def raiseSalary(self):
self.salary = self.salary * self.raiseAmount
@classmethod
def setRaiseAmount(cls, amount):
cls.raiseAmount = amount
@classmethod
def newFromString(cls, empstr):
first, surname, salary = empstr.split('-')
return cls(first, surname, salary)
@staticmethod
def whatDay(day):
num = day.weekday()
if num == 0:
print('\nLet\'s look at the bright side. At least Mondays only happen once a week')
if num == 1:
print('\nThank goodness Monday is gone. Happy Tuesday!')
if num == 2:
print('\nIt’s Wednesday. That means that we are over the hump!')
if num == 3:
print('\nHappy Thursday! P.S. It’s almost Friday!')
if num == 4:
print('\nHello Friday, where have you been all week?')
if num == 5:
print('\nSaturday is the perfect day for a wonderful adventure')
if num == 6:
print('\nOn this lovely Sunday...')
# class Writer(Employee):
#
# raiseAmount = 1.08
#
# def __init__(self, first, surname, salary, masterwork):
# Employee.__init__(self, first, surname, salary)
# self.masterwork = masterwork
#
# def infoSummary(self):
# return '{}, {}, \n{}, \n{}\n'.format(self.first + ' ' + self.surname,
# self.salary, self.email, self.masterwork)
#
# @classmethod
# def newFromString(cls, empstr):
# first, surname, salary, masterwork = empstr.split('-')
# return cls(first, surname, salary, masterwork)
#
#
# class Leader(Employee):
#
# def __init__(self, first, surname, salary, employees=None):
# super().__init__(first, surname, salary)
# if employees is None:
# self.employees = []
# else:
# self.employees = employees
#
# def infoSummary(self):
#
# nameList = []
#
# for e in self.employees:
# nameList.append(e.first + ' ' + e.surname)
#
# return '{}, {}, \n{}, \n{}\n'.format(self.first + ' ' + self.surname,
# self.salary, self.email, nameList)
#
# def addEmp(self, emp):
# if emp not in self.employees:
# self.employees.append(emp)
#
# def delEmp(self, emp):
# if emp in self.employees:
# self.employees.remove(emp)
#
# @classmethod
# def newFromString(cls, empstr):
# print('\nSorry, it does not work for Leader\n')
# empCharacter1 = Employee('Harry', 'Potter', 4000)
empCharacter1 = Employee('Harry')
empCharacter2 = Employee('Bilbo', 'Baggins', 6000)
# empWriter1 = Writer('Mark', 'Twain', 8000, 'The adventure of Tom Sawyer')
#
# empLeader = Leader('Julius', 'Caesar', 12000, [empCharacter1, empCharacter2])
#
# empStr1 = 'J.K-Rowling-10000-Harry Potter'
# empStr2 = 'J.R.R-Tolkien-8000-The lord of rings'
# empWriter2 = Writer.newFromString(empStr1)
# empWriter3 = Writer.newFromString(empStr2)
print(empCharacter1.infoSummary())
empCharacter1.surname = 'Potter'
print(empCharacter1.infoSummary())
# polymorphism and dunder method
class Employee(object):
__slots__ = ('__first', '__surname', '__salary', 'nickname')
raiseAmount = 1.04
employeeNum = 0
def __init__(self, first='Unknown', surname='Unknown', salary=0):
self.__first = first
self.__surname = surname
self.__salary = salary
Employee.employeeNum += 1
@property
def email(self):
return self.__first + '.' + self.__surname + This email address is being protected from spambots. You need JavaScript enabled to view it.'
@property
def fullname(self):
return self.__first + ' ' + self.__surname
@fullname.setter
def fullname(self, value):
if isinstance(value, str):
self.__first, self.__surname = value.split()
@property
def first(self):
return self.__first
@first.setter
def first(self, value):
if isinstance(value, str):
self.__first = value
else:
print('Firstname must be string')
@property
def surname(self):
return self.__surname
@surname.setter
def surname(self, value):
if isinstance(value, str):
self.__surname = value
else:
print('Surnamename must be string')
@property
def salary(self):
return self.__salary
@salary.setter
def salary(self, amount):
if isinstance(amount, int) or isinstance(amount, float):
self.__salary = amount
else:
print('Salary must be interger or float')
def infoSummary(self):
return '\n{}, {}, {}\n'.format(self.fullname,
self.salary, self.email)
def raiseSalary(self):
self.salary = self.salary * self.raiseAmount
@classmethod
def setRaiseAmount(cls, amount):
cls.raiseAmount = amount
@classmethod
def newFromString(cls, empstr):
first, surname, salary = empstr.split('-')
return cls(first, surname, salary)
@staticmethod
def whatDay(day):
num = day.weekday()
if num == 0:
print('\nLet\'s look at the bright side. At least Mondays only happen once a week')
if num == 1:
print('\nThank goodness Monday is gone. Happy Tuesday!')
if num == 2:
print('\nIt’s Wednesday. That means that we are over the hump!')
if num == 3:
print('\nHappy Thursday! P.S. It’s almost Friday!')
if num == 4:
print('\nHello Friday, where have you been all week?')
if num == 5:
print('\nSaturday is the perfect day for a wonderful adventure')
if num == 6:
print('\nOn this lovely Sunday...')
class Writer(Employee):
raiseAmount = 1.08
def __init__(self, first, surname, salary, masterwork=''):
Employee.__init__(self, first, surname, salary)
self.masterwork = masterwork
def infoSummary(self):
return '{}, {}, \n{}, \n{}\n'.format(self.fullname,
self.salary, self.email, self.masterwork)
@classmethod
def newFromString(cls, empstr):
first, surname, salary, masterwork = empstr.split('-')
return cls(first, surname, salary, masterwork)
def __add__(self, otherWriter):
if isinstance(otherWriter, Writer):
return '{} and {}'.format(self.masterwork, otherWriter.masterwork)
else:
return 'Kindly register {}\' masterwork at first, thanks'.format(otherWriter.fullname)
class Leader(Employee):
def __init__(self, first, surname, salary, employees=None):
super().__init__(first, surname, salary)
if employees is None:
self.employees = []
else:
self.employees = employees
def __repr__(self):
return '\n__repr__: {}\n'.format(self.infoSummary())
#
def __str__(self):
return '\n__str__: {}\n'.format(self.fullname)
def __len__(self):
return len(self.employees)
def infoSummary(self):
nameList = []
for e in self.employees:
nameList.append(self.fullname)
return '{}, {}, \n{}, \n{}\n'.format(self.fullname,
self.salary, self.email, nameList)
def addEmp(self, emp):
if emp not in self.employees:
self.employees.append(emp)
def delEmp(self, emp):
if emp in self.employees:
self.employees.remove(emp)
@classmethod
def newFromString(cls, empstr):
print('\nSorry, it does not work for Leader\n')
class Duck(object):
def infoSummary(self):
return '\nIn fact, I am a duck!\n'
def annualIncreaseRate(obj):
print('\nAnnual salary increase rate for {} is {}\n'.format(
type(obj).__name__, obj.raiseAmount))
def output(obj):
if hasattr(obj, 'infoSummary'):
print(obj.infoSummary())
else:
print('No comment' )
empCharacter1 = Employee('Harry', 'Potter', 4000)
empCharacter2 = Employee('Bilbo', 'Baggins', 6000)
empWriter1 = Writer('Mark', 'Twain', 8000, 'The adventure of Tom Sawyer')
empLeader = Leader('Julius', 'Caesar', 12000, [empCharacter1, empCharacter2])
empStr1 = 'J.K-Rowling-10000-Harry Potter'
empStr2 = 'J.R.R-Tolkien-8000-The lord of rings'
empWriter2 = Writer.newFromString(empStr1)
empWriter3 = Writer.newFromString(empStr2)
# print(type(empLeader))
# print(type(empLeader).__name__)
# polymorphism
# annualIncreaseRate(empCharacter1)
# annualIncreaseRate(empWriter1)
# annualIncreaseRate(empLeader)
# output(empLeader)
# output(empWriter2)
# output(empCharacter1)
# # #
# output('Harry Potter')
# #
# donaldDuck = Duck()
# output(donaldDuck)
# __repr__ and __str__
# print(empLeader)
# print(empLeader.__repr__())
# print(empLeader.__str__())
# __add__
# print(1+2)
# print(int.__add__(1, 2))
# print('glory ' + 'Godness')
# print(str.__add__('joy ' , 'Godness'))
#
# print(empWriter2 + empWriter3)
# print(empWriter2 + empLeader)
# __eq__ : Equal
# __ne__ : Not Equal
# __lt__ : Less Than
# __gt__ : Greater Than
# __le__ : Less Than or Equal
# __ge__ : Greater Than or Equal
# __add__ : Addition
# __sub__ : Subtraction
# __mul__ : Multiplication
# __div__ : Division
# __mod__ : Modulus
# __len__()
# print(len('blue moon'))
# print('blue moon'.__len__())
# print(len(empLeader))
# __slot__
empCharacter1.nickname = 'Pikachu'
print(empCharacter1.nickname)
# from datetime import date
#
# a = date.today()
# b = str(a)
# print(a)
# print(b)
# print(a.__str__())
# print(b.__str__())
# print(a.__repr__())
# print(b.__repr__())
class Employee(object):
__slots__ = ('__first', '__surname', '__salary', 'nickname')
raiseAmount = 1.04
employeeNum = 0
def __init__(self, first='Unknown', surname='Unknown', salary=0):
self.first = first
self.surname = surname
self.salary = salary
Employee.employeeNum += 1
@property
def email(self):
return self.first + '.' + self.surname + This email address is being protected from spambots. You need JavaScript enabled to view it.'
@property
def fullname(self):
return self.first + ' ' + self.surname
@fullname.setter
def fullname(self, value):
if isinstance(value, str):
self.first, self.surname = value.split()
@property
def first(self):
return self.__first
@first.setter
def first(self, value):
if isinstance(value, str):
self.__first = value
else:
print('Firstname must be string')
@property
def surname(self):
return self.__surname
@surname.setter
def surname(self, value):
if isinstance(value, str):
self.__surname = value
else:
print('Surnamename must be string')
@property
def salary(self):
return self.__salary
@salary.setter
def salary(self, amount):
if isinstance(amount, int) or isinstance(amount, float):
self.__salary = amount
else:
print('Salary must be interger or float')
def infoSummary(self):
return '\n{}, {}, {}\n'.format(self.fullname,
self.salary, self.email)
def raiseSalary(self):
self.salary = self.salary * self.raiseAmount
@classmethod
def setRaiseAmount(cls, amount):
cls.raiseAmount = amount
@classmethod
def newFromString(cls, empstr):
first, surname, salary = empstr.split('-')
return cls(first, surname, salary)
@staticmethod
def whatDay(day):
num = day.weekday()
if num == 0:
print('\nLet\'s look at the bright side. At least Mondays only happen once a week')
if num == 1:
print('\nThank goodness Monday is gone. Happy Tuesday!')
if num == 2:
print('\nIt’s Wednesday. That means that we are over the hump!')
if num == 3:
print('\nHappy Thursday! P.S. It’s almost Friday!')
if num == 4:
print('\nHello Friday, where have you been all week?')
if num == 5:
print('\nSaturday is the perfect day for a wonderful adventure')
if num == 6:
print('\nOn this lovely Sunday...')
class Writer(Employee):
raiseAmount = 1.08
def __init__(self, first, surname, salary, masterwork=''):
Employee.__init__(self, first, surname, salary)
self.masterwork = masterwork
def infoSummary(self):
return '{}, {}, \n{}, \n{}\n'.format(self.fullname,
self.salary, self.email, self.masterwork)
@classmethod
def newFromString(cls, empstr):
first, surname, salary, masterwork = empstr.split('-')
return cls(first, surname, salary, masterwork)
def __add__(self, otherWriter):
if isinstance(otherWriter, Writer):
return '{} and {}'.format(self.masterwork, otherWriter.masterwork)
else:
return 'Kindly register {}\' masterwork at first, thanks'.format(otherWriter.fullname)
class Leader(Employee):
def __init__(self, first, surname, salary, employees=None):
super().__init__(first, surname, salary)
if employees is None:
self.employees = []
else:
self.employees = employees
def __repr__(self):
return '\n__repr__: {}\n'.format(self.infoSummary())
#
def __str__(self):
return '\n__str__: {}\n'.format(self.fullname)
def __len__(self):
return len(self.employees)
def infoSummary(self):
nameList = []
for e in self.employees:
nameList.append(self.fullname)
return '{}, {}, \n{}, \n{}\n'.format(self.fullname,
self.salary, self.email, nameList)
def addEmp(self, emp):
if emp not in self.employees:
self.employees.append(emp)
def delEmp(self, emp):
if emp in self.employees:
self.employees.remove(emp)
@classmethod
def newFromString(cls, empstr):
print('\nSorry, it does not work for Leader\n')
class Duck(object):
def infoSummary(self):
return '\nIn fact, I am a duck!\n'
def annualIncreaseRate(obj):
print('\nAnnual salary increase rate for {} is {}\n'.format(
type(obj).__name__, obj.raiseAmount))
def output(obj):
if hasattr(obj, 'infoSummary'):
print(obj.infoSummary())
else:
print('No comment' )
empCharacter1 = Employee('Harry', 'Potter', 4000)
empCharacter2 = Employee('Bilbo', 'Baggins', 6000)
empWriter1 = Writer('Mark', 'Twain', 8000, 'The adventure of Tom Sawyer')
empLeader = Leader('Julius', 'Caesar', 12000, [empCharacter1, empCharacter2])
empStr1 = 'J.K-Rowling-10000-Harry Potter'
empStr2 = 'J.R.R-Tolkien-8000-The lord of rings'
empWriter2 = Writer.newFromString(empStr1)
empWriter3 = Writer.newFromString(empStr2)
# print(type(empLeader))
# print(type(empLeader).__name__)
# polymorphism
# annualIncreaseRate(empCharacter1)
# annualIncreaseRate(empWriter1)
# annualIncreaseRate(empLeader)
# output(empLeader)
# output(empWriter2)
# output(empCharacter1)
# # #
# output('Harry Potter')
# #
# donaldDuck = Duck()
# output(donaldDuck)
# __repr__ and __str__
# print(empLeader)
# print(empLeader.__repr__())
# print(empLeader.__str__())
# __add__
# print(1+2)
# print(int.__add__(1, 2))
# print('glory ' + 'Godness')
# print(str.__add__('joy ' , 'Godness'))
#
# print(empWriter2 + empWriter3)
# print(empWriter2 + empLeader)
# __eq__ : Equal
# __ne__ : Not Equal
# __lt__ : Less Than
# __gt__ : Greater Than
# __le__ : Less Than or Equal
# __ge__ : Greater Than or Equal
# __add__ : Addition
# __sub__ : Subtraction
# __mul__ : Multiplication
# __div__ : Division
# __mod__ : Modulus
# __len__()
# print(len('blue moon'))
# print('blue moon'.__len__())
# print(len(empLeader))
# __slot__
empCharacter1.nickname = 'Pikachu'
print(empCharacter1.nickname)
# from datetime import date
#
# a = date.today()
# b = str(a)
# print(a)
# print(b)
# print(a.__str__())
# print(b.__str__())
# print(a.__repr__())
# print(b.__repr__())