No.19面向对象

No.19

今日概要

  • 面向对象基本用法
  • 好处和应用场景
  • 面向对象的三大特性

内容详细

1.面向对象的基本格式

# 定义类
class 类名:
    def 方法名(self,name):
        print(name)
        return 666
    def 方法名(self):
        print(name)
        return 888
    
# 调用类中方法
obj = 类名()                # 1.创建类的对象
result = obj.方法名('alex') # 2.通过对象调用方法
print(result)

应用场景:遇到很多函数,需要给函数进行归类和划分。[封装]

class Redis:
    def redis_read(self):
        pass
    def redis_write(self):
        pass
    def redis_delete(self):
        pass
    def redis_update(self):
        pass

2.对象的作用

存储一些值,以后方便自己使用。

class File:
    def read(self):
        with open(self.xxx,mode='r',encoding='utf-8') as f:
            data = f.read()
        return data
    def write(self, content):
        with open(self.xxx, mode='a', encoding='utf-8') as f:
            f.write(content)

# 实例化了一个File类的对象
obj1 = File()
# 在对象中写了一个xxx = 'text.txt'
obj1.xxx = 'text.txt'
# 通过对象调用类中write方法,write方法中的self就是obj。
obj1.write('alex')

obj2 = File()
obj2.xxx = 'info.txt'
obj2.write('alex')
class Person:
    def show(self):
        print(self.name)
        
p1 = Person()
p1.name = '张三'
p1.show()

p2 = Person()
p2.name = '李四'
p2.show()
class Person:
    def show(self):
        temp = '我是%s,年龄%s,性别%s。'%(self.name, self.age, self.gender,)
        print(temp)
        
p1 = Person()
p1.name = '张三'
p1.age = 18
p1.gender = '男'
p1.show()

p2 = Person()
p2.name = '李四'
p2.age = 20
p2.gender = '男'
p2.show()
class Person:
    def __init__(self, a, b, c):
        self.name
        self.age
        self.gender
    
    def show(self):
        temp = '我是%s,年龄%s,性别%s。'%(self.name, self.age, self.gender,)
        print(temp)
        
# 类() 实例化对象,自动执行此类中的__init__方法。
p1 = Person('张三',18,'男')
p1.shouw()

p2 = Person('李四',20,'男')
p2.show()

# 总结:将数据封装到对象,方便使用。

总结

'''
如果写代码时,函数比较多比较乱
1.可以将函数归类并放入同一个类中。
2.函数如果有一个反复使用的公共值,则可以放到对象中。
'''
class File:
    def __init__(self,path):
        self.file_path = path

    def read(self):
        print(self.file_path)

    def write(self,content):
        print(self.file_path)

    def delete(self):
        print(self.file_path)

    def update(self):
        print(self.file_path)

p1 = File('test.txt')
p1.read()

p2 = File('info.txt')
p2.read()
循环让用户输入:用户名/密码/邮箱,输入完成后再进行数据打印。
# 以前写法:
USER_LIST = []
while True:
    user = input('请输入名字:')
    pwd = input('请输入密码:')
    user = input('请输入邮箱:')
    dic = {'username':user, 'password':pwd, 'email':email}
    USER_LIST.append(temp)

for item in USER_LIST:
    temp = '我的名字:%s,密码:%s,邮箱:%s。'%(item['username'], item['password'], item['email'])
    print(temp)
    
# 面向对象:
class Person:
    def __init__(self, user, pwd, email):
        self.username = user
        self.password = pwd
        self.email = email

USER_LIST = [对象(用户名/密码/邮箱),对象(用户名/密码/邮箱),对象(用户名/密码/邮箱)......]
while True:
    user = input('请输入名字:')
    pwd = input('请输入密码:')
    user = input('请输入邮箱:')
    p = Person(user, pwd, email)
    USER_LIST.append(p)
    
for item in USER_LIST:
    temp = '我的名字:%s,密码:%s,邮箱:%s。'%(item.username, item.password, item.email)
    print(temp)

# 面向对象
class Person:
    def __init__(self, user, pwd, email):
        self.username = user
        self.password = pwd
        self.email = email
    def info(self):
        return '我的名字:%s,密码:%s,邮箱:%s。'%(item.username, item.password, item.email)

USER_LIST = [对象(用户名/密码/邮箱),对象(用户名/密码/邮箱),对象(用户名/密码/邮箱)......]
while True:
    user = input('请输入名字:')
    pwd = input('请输入密码:')
    user = input('请输入邮箱:')
    p = Person(user, pwd, email)
    USER_LIST.append(p)
    
for item in USER_LIST:
    msg = item.info()
    print(msg)   

3游戏开发

class Police:
    def __init__(self, name):
        self.name = name
        self.hp = 10000
    
    def fight(self, name):
        msg = '%s去和%s战斗。'%(self.name, name)
        print(msg)

class Bandit:
    def __init__(self, nickname):
        self.name = nickname
        self.hp = 5000

    def murder(self, name):
        msg = '%s谋杀了%s。'%(self.nickname, name)
        print(msg)

p1 = Police('alex')        
b1 = Bandit('eric')

# eric去谋杀了alex,eric生命值-100,alex生命值-5000
b1.murder(p1.name)
b1.hp -= 100
p1.hp -= 5000
class Police:
    def __init__(self, name):
        self.name = name
        self.hp = 10000
    
    def dao(self, other):
        msg = '%s给了%s一刀。'%(self.name, other.nicname)
        self.hp -= 10
        other.hp -= 50
        print(msg)
    def qiang(self, other):
        msg = '%s给了%s一枪。'%(self.name, other.nicname)
        self.hp -= 100
        other.hp -= 500
        print(msg)
    def quan(self, other):
        msg = '%s给了%s一拳。'%(self.name, other.nicname)
        self.hp -= 2
        other.hp -= 10  
        print(msg)

class Bandit:
    def __init__(self, nickname):
        self.name = nickname
        self.hp = 5000

    def qiang(self, other):
        msg = '%s给了%s一枪。'%(self.nickname, other.name)
        self.hp -= 100
        other.hp -= 500
        print(msg)

p1 = Police('alex')        
b1 = Bandit('eric')
# alex给了eric一刀,又给了eric一拳;eric给了alex一枪。
p1.dao(b1)  
p1.quan(b1)
b1.qiang(p1)

4.继承

# 父类(基类)
class Base:
    def f1(self):
        pass
# 子类(派生类)
class Foo(Base):
    def f2(self):
        pass
 
# 创建了一个子类的对象
obj = Foo()
# 执行对象.方法时,优先在自己的类中找,如果没有就去父类中找。
obj.f2()
obj.f1()

# 创建了一个父类的对象
obj = Base()
obj.f1()

什么时候用到继承?多个类中如果有公共的方法,可以放到基类中避免重复编写。

class Base:
    def f1(self):
        pass

class Foo(Base):
    def f2(self):
        pass
    
class Bar(Base):
    def f3(self):
        pass
    
obj1 = Foo()
obj2 = Bar()

继承关系中查找方法的顺序

# 示例一
class Base:
    def f1(self):
        print('base.f1')
    
class Foo(Base):
    def f2(self):
        print('foo.f2')
    
obj = Foo()
obj.f1()
obj.f2()

# 示例二
class Base:
    def f1(self):
        print('base.f1')
    
class Foo(Base):
    def f2(self):
        self.f1()
        print('foo.f2')
        
obj = Foo()
obj.f2()

# 示例三
class Base:
    def f1(self):
        print('base.f1')
    
class Foo(Base):
    def f2(self):
        self.f1()
        print('foo.f2')
    def f1(self):
        print('foo.f1')
        
obj = Foo()
obj.f2()

# 示例四
class Base:
    def f1(self):
        self.f2()
        print('base.f1')
    def f2(self):
        print('base.f2')
    
class Foo(Base):
    def f2(self):
        print('foo.f2')
        
obj = Foo()
obj.f1()

# 示例五
class A:
    def f1(self):
        self.f2()
    def f2(self):
        pass
class B(A):
    pass
class C:
    pass
class D(C,B):
    pass

obj = D()
obj.f1()   

D类创建的对象,寻找f1方法顺序 D → C → B → A
f1方法调用了f2方法,又从D类开始寻找f2方法 D → C → B → A

注意事项:

  • self 到底是谁?
  • self 是哪个类创建的,就从此类开始找,自己没有就找父类。

5.多态(鸭子模型)

# python
def func(arg):      arg可以传入多种类型的数据
    v = arg[1]      传入数据类型必须有索引方法
    print(v)

# java
def func(str arg):  指定传入一种数据类型
    v = arg[1]
    print(v)

面试题:什么是鸭子模型

'''
就函数而言,python中对传入参数的类型不会限制,那么传入的参数就可以是各种数据类型,在函数中如果有例如arg.append方法,那么该方法就是对传入类型的一个限制。(传入类型必须有append方法)
这就是鸭子模型,类似于上述函数我们认为只要能嘎嘎叫的就是鸭子。(只要有append方法,就是我们想要的类型)
'''

总结

  1. 面向对象的三大特性:封装/继承/多态

    • 封装

      class File:
          def read(self):
              pass
          def write(self):
             pass
      class Person:
          def __init__(self,name,age)
             self.name = name
              self.age = age
      p = Person('alex',20)        
    • 继承

      class Base:
          pass
      class Foo(Base):
          pass
      • 多继承
      • self 到底是谁?
      • self 是哪个类创建,每次找方法的时候就从此类开始依次找。
    • 多态

      def fun(arg):   # arg可以传入多种类型数据
          arg.send()  # 必须具有send方法(嘎嘎叫)
  2. 格式和关键词

    class 类:
     def __init__(self, x):
            self.x = x
    
        def 方法(self, name)
         print(self.x, name)
    
    # 实例化一个对象
    v1 = 类(666)
    v1.方法('alex')

    三个词:

    • 对象
    • 方法
  3. 什么时候用面向对象?

    • 函数归类(业务功能多,可以使用面向对象)
    • 数据封装(创建字典储存数据时,可使用面向对象)
    • 游戏示例:创建一些角色并且根据角色需要再创建人物。

猜你喜欢

转载自www.cnblogs.com/elliottwave/p/12524534.html
今日推荐