# 格式
class Student:
name = 'swy' # 类属性
def f(): # 实例方法
print('实例方法')
@staticmethod
def g(): # 静态方法
print('静态方法')
@classmethod
def h(cls): # 类方法
print('类方法')
def __init__(self, name, age): # 初始化方法
self.name = name
self.age = age
语法: 实例名 = 类名()
stu = Student('swy', 23)
print(stu.name, stu.age)
# 第一种调用方式
stu.g()
stu.h()
stu.m()
# 第二种调用方式
Student.m(stu)
Student.h()
Student.h()
stu = Student('swy', 23)
# 动态绑定属性
stu.gender = '男'
print(stu.gender)
def show():
print('show')
# 动态绑定方法
stu.show = show
stu.show()
class Car:
def __init__(self, name):
self.__name = name #name不希望在类的外部被使用,所以加了两个_
def start(self):
print('启动中...')
car = Car('宝马')
car.start()
print(car.name)
class 子类类名( 父类1, 父类2... ):
pass
# 父类
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
def info(self):
print('姓名:{0} 年龄:{1}'.format(self.name, self.age))
# 子类
class Student(Person):
def __init__(self, name, age, score):
super().__init__(name, age)
self.score = score
# 实例化子类
stu = Student('swy', 23, 59)
stu.info() # 子类继承的父类的方法
obj = object()
print(dir(obj))
结果:
[‘class’, ‘delattr’, ‘dir’, ‘doc’, ‘eq’, ‘format’, ‘ge’, ‘getattribute’, ‘gt’, ‘hash’, ‘init’, ‘init_subclass’, ‘le’, ‘lt’, ‘ne’, ‘new’, ‘reduce’, ‘reduce_ex’, ‘repr’, ‘setattr’, ‘sizeof’, ‘str’, ‘subclasshook’]
class Student:
def __init__(self, name):
self.name = name
def __str__(self): # 重写__str__()方法
return '重写__str__(): name: {0}'.format('swy')
stu = Student('swy')
print(stu)
class Animal(object):
def eat(self):
print('动物会吃')
class Dog(Animal):
def eat(self):
print('狗会吃')
class Cat(Animal):
def eat(self):
print('猫会吃')
def eat(obj):
obj.eat()
eat(Animal())
eat(Dog())
eat(Cat())
特殊属性 | 描述 |
---|---|
__dict__ | 获得类对象或实例对象所绑定的所有属性和方法的字典 |
特殊方法 | 描述 |
---|---|
__len__() | 通过重写该方法,让内置函数len()的参数可以是自定义类型 |
__add__() | 通过重写该方法,可以使自定义对象具有"+"功能 |
__new__() | 用于创建对象 |
__init__() | 对创建的对象进行初始化 |
class CPU:
pass
class Disk:
pass
class Computer:
def __init__(self, cpu, disk):
self.cpu = cpu
self.disk = disk
cpu = CPU()
disk = Disk()
computer = Computer(cpu, disk)
# 浅拷贝
import copy
print('--------浅拷贝--------')
computer2 = copy.copy(computer)
print(computer, computer.cpu, computer.disk)
print(computer2, computer2.cpu, computer2.disk)
# 深拷贝
print('\n--------深拷贝--------')
computer3 = copy.deepcopy(computer)
print(computer, computer.cpu, computer.disk)
print(computer3, computer3.cpu, computer3.disk)