Skip to content

面向对象

  • 面向对象编程(Object-Oriented Programming,简称 OOP)是一种编程范式,它以"对象"为核心组织代码和数据。

  • 格式
python
class 类名:
    pass

构造方法

  • 初始化方法,类被实例化时自动执行
python
class Person:
    # 构造方法
    def __init__(self, name, age):
        self.name = name
        self.age = age

self 说明

  • self 是一个特殊的参数,它指向实例本身
  • self 必须是第一个参数
  • self 可以自定义,但是建议使用 self

类的属性

  • 普通属性 其他文件 import 可以访问
  • _ 单_开头拥有 protected 权限;本文件其他类可以访问,其他文件 import 不能直接访问。
  • __ 双__开头拥有 private 权限;本文件其他类不能访问,其他文件 import 不能直接访问。
python
class Person:
	# 类的变量
	name = ''
	age = 0
	_weight = 0
	__height = 0

	def __init__(self, name, age, weight, height):
		self.name = name
		self.age = age
		self._weight = weight
		self.__height = height

	@property  # 获取私有属性
	def height(self):
		return self.__height

	@height.setter  # 设置私有属性
	def height(self, height):
		self.__height = height


judy = Person('judy', 18, 60, 160)
print(judy.name)
print(judy._weight)     # 60
# print(judy.__height)  # 会报错
print(judy.height)      # 160
judy.height = 140
print(judy.height)      # 140

类的方法

  • _ 单_开头拥有 protected 权限;本文件其他类可以访问,其他文件 import 不能直接访问。
  • __ 双__开头拥有 private 权限;本文件其他类不能访问,其他文件 import 不能直接访问。
  • @staticmethod 静态方法,没有 self 参数,可以直接通过类名调用
python
class Person:
	name = ''
	age = 0
	_weight = 0
	__height = 0

	def __init__(self, name, age, weight, height):
		self.name = name
		self.age = age
		self._weight = weight
		self.__height = height

	def eat(self):
		print(self.name + '在吃东西')

	# 私有方法
	def _weight_increase(self):
		self._weight += 1
		print(self._weight)

	# 私有方法
	def __height_increase(self):
		self.__height += 1
		print(self.__height)

	@staticmethod
	def run():
		print("cat run")

judy = Person('judy', 1, 60, 120)
judy.eat()
judy._weight_increase()  # 61
# judy.__height_increase()  # 会报错
Person.run()  # 直接调用静态方法,无需实例化

继承

  • 继承其他类并使用其属性和方法
  • 尽量单继承,多继承会导致代码复杂,维护起来困难
python
class Person:
	name = ''
	age = 0
	weight = 0  # 私有属性,只能在类内部访问

	def __init__(self, name, age, weight):
		self.name = name
		self.age = age
		self.weight = weight

	def eat(self):
		print(self.name + '在吃东西')


class Monitor:
	def __init__(self, name, age, weight):
		self.name = name
		self.age = age
		self.weight = weight

	def watch(self):
		print(self.name + '在观看')


# 继承类,可以多个继承
class Student(Person, Monitor):
	def __init__(self, name, age, weight, score):
		super().__init__(name, age, weight)
		self.name = name
		self.age = age
		self.weight = weight
		self.score = score

	def study(self):
		print(self.name + '在学习')

	# 重写父类的方法
	def watch(self):
		print(self.name + '在观看student')


zhangsan = Student('zhangsan', 18, 70, 100)
zhangsan.study()
zhangsan.eat()
zhangsan.watch()

多态

  • 同一种行有不同形式
  • 函数的参数是一个对象,调用这个函数时,传入不同的对象,会有不同的行为
python
class Animal(object):
	def eat(self):
		print("animal eat")

class Dog(Animal):
	def eat(self):
		print("dog eat")

class Cat(Animal):
	def eat(self):
		print("cat eat")

def func(obj):
	obj.eat()

func(Dog())

单例模式

  • 确保一个类只有一个实例
  • 提供一个全局访问点
python
class Singleton:
	__instance = None

	@classmethod
	def get_instance(cls):
		if cls.__instance is None:
			cls.__instance = cls()
		return cls.__instance

__new__()方法

在类名()示例化时

  1. python 解释器会先调用__new__()方法
  2. 然后进行内存空间分配
  3. 返回一个对象的引用
  4. 再把对象的引用传给__init__()方法,初始化实例对象
python
class Animal(object):
	def __new__(cls, *args, **kwargs):
		print("创建对象,分配内存空间")

		# 调用父类的__new__方法创建对象 必须返回这个
		instance = super().__new__(cls)
		return instance

	def __init__(self, name, age):
		print("初始化对象")
		self.name = name
		self.age = age

animal = Animal("张三", 18)
print(animal)