day23面向对象小案例
1.案例
"""
题目:
定义一个类,产生一堆对象
要求:
要有一个计数器,记录一共差生了多少个对象
"""
class Student():
count = 0
def __init__(self,name,age):
self.name=name
self.age=age
Student.count+=1
stu1=Student('e',18)
stu2=Student('g',18)
stu3=Student('o',18)
stu4=Student('n',18)
print(stu4.count)
print(stu3.count)
print(stu2.count)
print(stu1.count)
4
4
4
4
1.1小练习
"""
题目:
定义两个英雄类
1. 每个英雄都要有昵称, 生命值,攻击力
2. 实例化出两个对象
3. 两个英雄互相殴打,掉血。
"""
class demaxiya():
def __init__(self,name,health,attack):
self.name=name
self.health=health
self.attack=attack
def kill(self,enemy):
enemy.health-=self.attack
class nuokesasi():
def __init__(self, name, health, attack):
self.name=name
self.health=health
self.attack=attack
def kill(self,enemy):
enemy.health-=self.attack
zhaoxin=demaxiya('赵信',200,25)
ktln=nuokesasi('卡特琳娜',200,20)
print('卡特琳娜初始生命值为%s'% ktln.health)
print('赵信初始生命值为%s'% zhaoxin.health)
print('-----------------------------------')
zhaoxin.kill(ktln)
ktln.kill(zhaoxin)
print('卡特琳娜收到攻击后生命值为%s'% ktln.health)
print('赵信收到攻击后生命值为%s'% zhaoxin.health)
卡特琳娜初始生命值为100
赵信初始生命值为200
-----------------------------------
卡特琳娜收到攻击后生命值为75
赵信收到攻击后生命值为180
2.绑定方法
1. 绑定给对象的
2. 绑定给类的
总结:
1. 绑定给对象的
对象来调用,把对象自己当成第一个参数传递
2. 绑定给类的方法
@classmethod
类来调用,把类名当成第一个参数传递
对象也可以调用但是不会传东西,因为传的是类名当成第一个参数传递
import settings
class Mysql:
school = 'SH'
def __init__(self, ip, port):
self.ip = ip
self.port = port
@classmethod
def func(cls):
print(cls)
return cls(settings.IP, settings.PORT)
obj = Mysql(settings.IP, settings.PORT)
obj2 = obj.func()
3.非绑定方法
class Student ():
def __init__(self,name,age):
self.name=name
self.age=age
self.id=self.create_id()
@staticmethod
def create_id():
import uuid
return uuid.uuid4()
msg=Student('张三',18)
print(msg.id)
print(msg.create_id())
print(Student.create_id())
4.如何隐藏属性
隐藏属性特点:
1. 在类定义阶段发生了变形: _类名__属性名
2. 对内不对外,类内部可以访问 外部不行
为什么要隐藏:
对内部的属性或者方法做隐藏,可以更好的限制外部使用者, 要想让外部访问,在类内部定义对外可访问的接口。
class Student():
__school = 'SH'
def __init__(self, name):
self.__name = name
def __func(self):
print('func')
def get_school(self):
return self.__school
def set_school(self, v):
if type(v) is not str:
return
self.__school = v
def get_func(self):
return self.__func()
obj = Student('egon')
obj.set_school(123)
print(obj._Student__school)
5. property装饰器
property装饰器: 就是将函数功能封装成数据属性
class Student():
__school = 'SH'
__name = 'egon'
def __init__(self, name):
self.__name = name
def __func(self):
print('func')
@property
def name(self):
return self.__name
@name.setter
def name(self, v):
self.__name = v
@name.deleter
def name(self):
print("不让删除")
obj = Student('egon')
print(obj.get_name)
obj.set_name('xyz')
print(obj.name)
obj.name = 'xyz'
print(obj.name)
del obj.name
return self.__name
def set_name(self, v):
self.__name = v
def del222_name(self):
print("不让删除")
xxxx = property(get_name,set_name,del222_name)
obj = Student()
print(obj.xxxx)
obj.xxxx = 'x'
print(obj.xxxx)