python面对对象小汇总
类的起名规则
# 所有的类名要求首字母大写,多个单词使用驼峰式命名法 如 ValueError
# 类中方法: 普通方法 类方法 静态方法 魔术方法
class Phone:
# 类属性
brand = "vivo"
price = 2999
type = "Z5 pro"
# 魔术方法 系统默认执行
def __init__(self, owner="徐坤坤"): # init 初始化 ,owner可以外界传参
print("--------init")
self.owner = owner
# 类里面的方法
def call(self):
print("self.......", self)
print(self.note) # 不能保证每个self都有note
print(f"{self.owner} 拿着 {self.brand} 手机 ,跑步,价值 {self.price}")
print("正在法典化")
zzk = Phone("立农")
print(zzk.brand)
print(zzk)
zzk.note = "我是zk的通讯录"
zzk.call()
class Cat:
type = "猫"
def __init__(self, nickname, age, color):
self.nickname = nickname
self.age = age
self.color = color
def eat(self, food):
print(f"{self.nickname} like {food}")
def catch_mouse(self, color, weight):
print(f"{self.nickname} 抓了 {color}色 重{weight}kg 的 杰瑞")
def sleep(self, hour):
if hour < 5:
print("sleep! baby")
else:
print('get up!baby,let"s catch mice')
def show(self):
print("my baby detailed information---->")
print(self.color, self.nickname, self.age)
# 类方法
class Dog:
# 类属性
aa = "阿发"
__age = 18 # 私有化,外界不能直接访问
def __init__(self, name="欢欢"):
self.name = name
def run(self):
print(f"{self.name} run to me")
def eat(self):
print("eat bone")
self.run() # 类中方法的调用,需要通过self
# 以下是类方法 不需要依赖对象
@classmethod
def test(cls):
print(cls) # 指的是 的类
# print(cls.name) 不能用
cls.__age = 20 # 修改类属性
print(f"我是{cls.aa} {cls.__age}") # 类方法不能使用
# 静态方法
@staticmethod # 不能使用self.方法
def test1():
print("-------->静态方法")
print(Dog.__age) # 不能使用类中对象属性
# 静态方法:很类似类方法
# 1.需要加@staticmethod
# 2.无需传递参数
# 3.也只能访问类属性和方法,对象的不行
# 4.加载时机同类方法
类方法 静态方法
不同:
1.装饰器不同
2.类方法是有参数的,静态方法没有参数
相同:
1.只访问类的属性和方法,对象是无法访问的
2.都可以通过类名调用访问
3.都可以在创建对象之前使用,因为是不依赖于对象
class Person:
def __init__(self, name):
print("------->init", self)
self.name = name
def __str__(self):
return "姓名是"
def __new__(cls, *args, **kwargs):
print("------->new")
postion = object.__new__(cls) #
print(postion)
return postion # 地址返给对象self
def __call__(self, name):
print("---------->call")
print("我执行的对象参数是:", name)
def __del__(self): # 程序结束前的最后一步会执行这个
print("结束啦")
# del p # NameError: name 'p' is not defined 删除了,再引用就会报错
p = Person("jack")
print("sdfg", p)
# 查看引用的次数
import sys
t = sys.getrefcount(p) # 自身引用也算一次
print(t)
# 私有化 __属性"
# """
# 好处:
# 1.隐藏属性,不被外界修改
# 2.修改同过函数修改 set属性名,并添加限制条件
# """
# 封装: 1.私有化属性 2.定义公有set和get方法
# 开发中私有化
import random
class Student:
def __init__(self, name, age):
self.name = name
self.__age = age
self.__score = 95
# 老版本
# 定义公有set和get
# set 为了赋值
def setAge(self, age):
if age > 0 and age <= 100:
self.__age = age
else:
print("年龄不在范围内")
# get 用于取值
def getAge(self):
return self.__age
# 新版本
@property
def score(self):
return self.__score
@score.setter
def score(self, score):
if score > 100:
print("wrong")
else:
self.__score = score
def __str__(self):
return f"姓名:{self.name},age:{self.__age},score:{self.__score}"
zzk = Student("zzk", 16)
zzk.setAge(18)
print(zzk.getAge())
print(zzk)
zzk.score = 99 # 设置了条件
print(zzk.score) # 新版本中,私有化变量可以直接访问
print(zzk.__dir__())
print(zzk._Student__score) # 这种访问方法不推荐
print("---------------------------------------------------")
# 公路 和 车
class Road:
def __init__(self, name, length):
self.name = name
self.length = length
class Car:
def __init__(self, name, speed):
self.name = name
self.speed = speed
def get_time(self, road):
ran_time = random.randint(1, 10)
msg = f"{self.name} 的车 速度:{self.speed} run:{ran_time} on {road}"
print(msg)
def __str__(self):
return self.name+str(self.speed)
# 创建实例对象
r = Road("小路", 12000)
benchi = Car("奇瑞", 120)
benchi.get_time(r.name)
print(benchi)
继承
# 知识点:
# 1.has a 一个类中使用了另外一种自定义的类型
# 2.类型:系统 int float
# 自定义 自定义类 student
#
# 3.is a
# 继承,减少代码冗余
# 父类提供的方法不能满足子类的需求,就需要在子类中定义一个同名的方法,这种行为:重写
# <>
class Person:
def __init__(self, name, love):
self.name = name
self.love = love
def run(self):
print("i can run")
class Student(Person):
def __init__(self, name, love, teacher):
self.teacher = teacher
print("i am student init", self.teacher)
# 如何调用父类的__init__
super(Student, self).__init__(name, love) # super 相当于父类的对象
# 这边相当于一个判断
def run(self):
print("我跑啦,哈哈哈")
zzk = Student("zzk", "烤鸭", "hld")
zzk.run()
print(zzk.love)
class Person:
def __init__(self, no, name, salary):
self.no = no
self.name = name
self.salary = salary
def __str__(self):
msg = f"工号:{self.no} \n 姓名: {self.name} \n 工资:{self.salary}"
return msg
def getSalary(self):
return self.salary
class Worker(Person):
def __init__(self, no, name, salary, hours, per_hour):
super().__init__(no, name, salary)
self.hours = hours
self.per_hour = per_hour
def getSalary(self):
money = self.hours * self.per_hour
self.salary += money
return self.salary
class Saleman(Person):
def __init__(self, no, name, salary, salemoney, percent):
super().__init__(no, name, salary)
self.salemoney = salemoney
self.percent = percent
def getSalary(self):
money = self.salemoney * self.percent
self.salary += money
return self.salary
# 创建对象
w = Worker("001", "康", 2000, 150, 60)
x = w.getSalary()
print("月薪:", x)
print("-----------------------------")
saler = Saleman("002", "lucy", 5000, 5000000, 0.003)
s = saler.getSalary()
print("月薪:", s)
print(s)
# 多继承
class A:
def test(self):
print("-----------AAAAAA")
class B:
def test1(self):
print("----------BBBBB")
class C(A, B):
def test2(self):
print("-----CCCC")
c = C()
c.test()
c.test1()
c.test2()
"""
python 允许多继承
def 子类(父类1,父类2)
多继承搜索顺序
广度优先
python2 是 从左到右,深度优先
"""
print(C.__mro__) # 显示搜索顺序
# isinstance(obj,类) 判断obj 是不是类的对象或者判断obj是不是该子类的对象