跳到主要内容

基本概念

self 参数
  • 类中所有方法必备的首个参数;
  • 代表实例本身。

定义类

class ClassName([ParentClass]):
"""docstring"""

def __init__(self, args):
suite

def function_name(self, args):
suite
__int__() 方法
  • python 特殊方法,必须使用;
  • 创建实例时自动运行;
def __init__(self, args):
"""docstring"""
self.attribute = value

创建实例

创建实例
instance_name = ClassName(args)
实例的隔离机制
  • 不同实例 (名称不同) 相互隔离,
  • 作为单独个体,互不影响。
调用实例
# 调用属性
instance.attribute
# 调用方法
instance.method()
className.method(instance)

属性

定义属性
def __init__(self, args):
"""docstring"""
self.attribute = value
设置属性默认值
def __init__(self, args):
"""docstring"""
self.attribute = default_value

def __init__(self, args, attribute = default_value):
"""docstring"""
self.attribute = attribute
修改属性
# 直接修改
instance_name.attribute = new_value
class ClassName():
--snip--

def function_name(self):
self.attribute = new_value

# 通过方法修改
class ClassName():
--snip--

def update_attribute(self, update_value):
self.attribute = update_value

instance_name.update_attribute(update_value)
class ClassName():
--snip--

def function_name(self):
self.update_attribute(update_value)
类作为属性
class AttributeClass():
"""docstring"""

def __init__(self, args):
suite

def function_name(self, args):
suite

class ClassName():
"""docstring"""

def __init__(self, args):
self.attribute = AttributeClass()

def function_name(self, args):
suite

# 调用
instance_name.attribute.attribute
instance_name.attribute.method()

静态方法和类方法

静态方法
  • 使用 staticmethod 装饰器;
  • 不需要定义 self 参数;
类方法
  • 使用 classmethod 装饰器;
  • 第一个参数恒为 cls 参数;
class Animal:
def __init__(self, name):
self.name = name

def run(self):
print(f"{self.name}跑起来啦")

@staticmethod
def eat():
print("正在吃饭...")

@classmethod
def jump(cls, name):
print(f"{name}跳起来啦")

私有属性和私有方法

私有属性
  • _var:告知其为私有属性,非强制性;
  • __var:python 解释器重写属性为 _className__var,强制性;
私有方法
  • 同私有属性;

继承

单继承

单继承
class ChildClass(ParentClass):
"""docstring"""

def __init__(self, args):
super.__init__(args)
suite

def function_name(self, args):
suite
super.__int__() 方法
  • python 魔法方法,必须使用;
  • 位于子类 __int__() 方法中;
  • 将父类属性和方法继承给子类;
覆写父类属性和方法
  • 定义父类同名属性和方法,
  • python 将忽略父类对应属性和方法,
  • 执行子类对应属性和方法。

多继承

多继承
class ChildClass(ParentClass1, ParentClass2, ...):
"""docstring"""

def __init__(self, args):
super.__init__(args)
suite

def function_name(self, args):
suite

装饰器

@abstractmethod
  • 定义抽象类;
  • 导入 ABC,使用 @abstractmethod 装饰器
from abc import ABC
from abc import abstractmethod

class Database(ABC):
@abstractmethod
def query(self, *args):
pass

@staticmethod
@abstractmethod
def execute(sql_string):
pass
@property
  • 表示函数返回一个类的属性;
class example(object):
@property
def method(self):
return 123

test=example()
test.method # 123