一、类
1、定义
用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。
2、格式
所有的类名要求首字母大写,多个单词使用驼峰式命名
class 类名[(父类)]:
属性: 特征
方法: 动作
例子1:
class Phone:
# 属性
brand = 'huawei'
# 方法
print(Phone)
# 使用类创建对象
yp = Phone()
print(yp)
print(yp.brand)
yp.brand = 'iphone'
print(yp.brand)
feifei = Phone()
print(feifei)
print(feifei.brand)
feifei.brand='iphone xxs'
print(feifei.brand)
xiaowei = Phone()
print(xiaowei.brand)
例子2:
# 定义类和属性
class Student:
# 类属性
name = 'xiaowei'
age = 2
# 使用类创建对象
xiaowei = Student()
# 对象属性
xiaowei.age = 18
print(xiaowei.age)
print(xiaowei.name)
Student.name = 'feifei'
ruirui = Student()
print(ruirui.name)
二、方法
1、定义
类中方法:动作
种类:普通方法 类方法 静态方法 魔术方法
方法间调用:
class A:
def a(self):
pass
def b(self):
# 调用a方法
self.a()
案例:
# 案例
# 猫
class Cat:
type = '猫'
# 通过__init__初始化特征
def __init__(self,nickname,age,color):
self.nickname = nickname
self.age = age
self.color = color
# 动作:方法
def eat(self,food):
print('{}喜欢吃{}'.format(self.nickname,food))
def catch_name(self,color,weight):
print('{},抓了一只{}kg,{}的大老鼠'.format(self.nickname,weight,color))
def sleep(self,hour):
if hour < 5:
print('继续睡&