继承
子类自动继承父类的所有方法和属性
继承的语法:
class 类名 (父类名)
pass
1. 子类继承父类, 可以直接使用父类中已经封装好的方法, 不需要再次开发
2. 子类可以根据需求, 封装自己特有的属性和方法
3. 当父类中的方法满足不了子类的需求时, 可以对方法进行重写
例如:
- import math
- # 类的继承
- class Shape():
- def __init__(self,color):
- self.color = color
- def area(self):
- return None
- def show_color(self):
- print(self.color)
- class Circle(Shape):
- def __init__(self,color,r):
- super().__init__(color)
- self.r = r
- def area(self):
- return math.pi*self.r*self.r
- class Rectingle(Shape):
- def __init__(self,color,Height,Width):
- super().__init__(color) #记得给 super 加上 ()
- self.Height = Height
- self.Width = Width
- def area(self):
- return self.Width*self.Height
- circle = Circle('blue',5.0)
- print(circle.area())
- circle.show_color()
- recent = Rectingle('red',5.0,2.0)
- print(recent.area())
- recent.show_color()
结果:
- 78.53981633974483
- blue
- 10.0
- red
__new__方法
python 中定义的类, 在创建实例对象的时候, 会自动执行 init() 方法, 但是在执行 init() 方法之前, 会执行 new() 方法
__new()__的作用有两个
1. 在内存中为内存分配空间
2. 返回对象的引用 (对象的内存地址)
python 解释器在获得引用的时候会将其传递给 init() 方法中的 self
- class A():
- def __new__(cls, *args, **kwargs):
- print('__new__')
- return super().__new__(cls) #这里一定要返回, 否则 init 不会被执行
- def __init__(self): #这里的 self 就是 new 方法中的 return 返回值
- print('__init__')
- a = A()
结果:
__new__ __init__
单例模式
如果我们创键两个实例 a1 = A()
a2 = A()
那么我们使用 id(a1),id(a2) 会发现值是不同的, 也就是说我们创键了两个实例对象, 用了两份内存地址
如果我们想先创建一个实例对象, 之后不管创键多少个, 返回的永远是第一个实例对象的内存地址, 那么我们可以这样实现
- # 单例模式
- # 重写 new 方法很固定, 返回值必须是这个
- # 这样就避免了创键多份
- # 创键第一个实例的时候,_instance 还是 None, 那么会分配空间创键实例
- # 此时类属性已经被修改,_instance 不再为 None
- # 那么当后面实例属性被创建的时候, 由于_instance 不为 None
- # 则返回第一个实例对象的引用, 即内存地址
- class B():
- _instance = None
- def __new__(cls, *args, **kwargs):
- if B._instance == None:
- B._instance = super().__new__(cls)
- return B._instance
- a = B()
- print(id(a))
- b = B()
- print(id(b))
结果:
- 2706206100280
- 2706206100280
来源: https://www.cnblogs.com/xy-l/p/11246567.html