本系列博文基于廖雪峰老师的官网Python教程,笔者在大学期间已经阅读过廖老师的Python教程,教程相当不错,官网链接: 廖雪峰官方网站.请需要系统学习Python的小伙伴到廖老师官网学习,笔者的编程环境是Anaconda+Pycharm,Python版本:Python3.
1.使用__slots__
class Employee(object):
pass
employee1 = Employee()
employee1.name = "Willard"
print("employee1.name属性为:", employee1.name)
def setSalary(self, salary):
self.salary = salary
from types import MethodType
employee1.setSalary = MethodType(setSalary, employee1)
employee1.setSalary(20000)
print("employee1.salary结果为:", employee1.salary)
employee2 = Employee()
def setRank(self, rank):
self.rank = rank
Employee.setRank = setRank
employee1.setRank("A")
print("employee1等级:", employee1.rank)
employee2.setRank("B")
print("employee2等级:", employee2.rank)
employee1.name属性为: Willard
employee1.salary结果为: 20000
employee1等级: A
employee2等级: B
class Employee(object):
__slots__ = ("name", "salary")
employee1 = Employee()
employee1.name = "ChenJD"
employee1.salary = 20000
class OtherEmployee(Employee):
pass
otherEmployee1 = OtherEmployee()
otherEmployee1.rank = "A"
print("otherEmployee1可以绑定rank属性:",otherEmployee1.rank)
2.使用@property
class Employee(object):
def getSalary(self):
return self._salary
def setSalary(self, value):
if not isinstance(value, int):
raise ValueError("Salary must be an integer.")
if value < 0:
raise ValueError("Salary must be > 0.")
self._salary = value
employee1 = Employee()
employee1.setSalary(20000)
print("employee1.getSalary结果:", employee1.getSalary())
class Employee(object):
@property
def salary(self):
return self._salary
@salary.setter
def salary(self, value):
if not isinstance(value, int):
raise ValueError("Salary must be integer.")
if value < 0:
raise ValueError("Salary must be > 0.")
self._salary = value
employee2 = Employee()
employee2.salary = 15000
print("employee2.salary的结果:", employee2.salary)
3.多重继承
"""
Animal
---Mammal
------Dog
------Bat
---Bird
------Parrot
------Ostrich
"""
"""
Animal
---Runnable
------Dog
------Ostrich
---Flyable
------Parrot
------Bat
"""
class Animal(object):
pass
class Mammal(Animal):
pass
class Bird(Animal):
pass
class Dog(Mammal, RunnableMixIn):
pass
class Bat(Mammal, FlyableMixIn):
pass
class Parrot(Bird, FlyableMixIn):
pass
class Ostrich(Bird, RunnableMixIn):
pass
class RunnableMixIn(object):
def run(self):
print("Running...")
class FlyableMixIn(object):
def fly(self):
print("Flying...")
|