一. python面向对象基础

一. 面向对象(OOP)

面向对象 首先 要设计类
    类名:   见名之之意  首字母大写   其他遵循驼峰命名法
    属性 :见名之意  其他遵循驼峰命名法
    行为:(方法/功能) :见名之意   其他遵循驼峰命名法


类名:car
属性:  color   type
行为: 跑


创建类: 
      类:一种数据类型 本身并不占空间 根据所学过的 number string boolean 等类似
      用类创建实例化(变量)  对象占内存空间



格式:
   class 类名 (父类列表):
          属性
          行为

# 创建一个简单的类
class ClassName(object):
       name=""
       age=0
       height=0
       weight=0
       # 定义方法(定义函数)
       # 注意: 方法参数必须self 当第一个参数
       self 代表类的实例(某个对象)
          def run(self):
             print("run")
def eat(self,food): print("eat"+food)
# 创建一个简单的类
class person(object):

  # 实例化对象
       name=""
       age=0
       height=0
       weight=0

       定义方法(定义函数)
       注意: 方法参数必须self 当第一个参数

       self 代表类的实例(某个对象)
       
       def run(self):
          print("run")

       def eat(self,food):
         print("eat"+food)
# 实例化对象
#        格式:对象名=类名(参数列表)    注意:没有参数列表小括号也不能省略

per1=person()
print(per1)

per2=person()
print(per2)
# 创建一个简单的类
class person(object):
  # 实例化对象
       name=""
       age=0
       height=0
       weight=0
       # 定义方法(定义函数)
       # 注意: 方法参数必须self 当第一个参数
       # self 代表类的实例(某个对象)
       def run(self):
          print("run")

       def eat(self,food):
         print("eat"+food)

# 实例化对象
#        格式:对象名(变量名)=类名(参数列表)    注意:没有参数列表小括号也不能省略

per1=person()
print(per1)  # <__main__.person object at 0x024E37D0>
print(type(per1))  #<class '__main__.person'>
print(id(per1))   #33731888



per2=person()
print(per2) # <__main__.person object at 0x024E3870>
print(type(per1))  #<class '__main__.person'>
print(id(per2))    #33731984
# 创建一个简单的类
class person(object):
    # 实例化对象
    name = ""
    age = 0
    height = 0
    weight = 0

    # 定义方法(定义函数)
    # 注意: 方法参数必须self 当第一个参数

    # self 代表类的实例(某个对象)

    def run(self):
        print("run")

    def eat(self, food):
        print("eat" + food)

    def openDoor(self, food):
        print("我已经打开了冰箱门")

    def filEle(self):
        print("我已经把大象装进了冰箱了哈哈哈")

        def closeDoor(self):
            print("我已经关闭了冰箱门")

# 实例化对象

#        格式:对象名(变量名)=类名(参数列表)    注意:没有参数列表小括号也不能省略

per1 = person()
print(per1)  # <__main__.person object at 0x00000258FC573C88>
# 创建一个简单的类
class person(object):
    # 实例化对象
    name = "哈哈"
    age = 56
    height = 150
    weight = 78
    # 定义方法(定义函数)
    # 注意: 方法参数必须self 当第一个参数
    # self 代表类的实例(某个对象)

    def run(self):
        print("run")

    def eat(self, food):
        print("eat" + food)

    def openDoor(self, food):
        print("我已经打开了冰箱门")

    def filEle(self):
        print("我已经把大象装进了冰箱了哈哈哈")

    def closeDoor(self):
        print("我已经关闭了冰箱门")

# 实例化对象
#        格式:对象名(变量名)=类名(参数列表)    注意:没有参数列表小括号也不能省略

# 访问属性:
#         格式 : 对象名.属性名
#          赋值 : 对象名.属性名 =新值

per1 = person()
# 如果创建的类里面的属性带有参数 就用默认参数   没有就传参数

per1.name = "张三"
per1.age = 25
per1.height = 165
per1.weight = "80kg"

print(per1.name, per1.age, per1.height, per1.weight)  # 张三 25 165 80kg
# 创建一个简单的类
class person(object):
    # 实例化对象
    name = ""
    age = 0
    height = 0
    weight = 0
    # 定义方法(定义函数)
    # 注意: 方法参数必须self 当第一个参数
    # self 代表类的实例(某个对象)

    def run(self):
        print("run")

    def eat(self, food):
        print("eat" + food)

    def openDoor(self):
        print("我已经打开了冰箱门")

    def filEle(self):
        print("我已经把大象装进了冰箱了哈哈哈")

    def closeDoor(self):
        print("我已经关闭了冰箱门")

# 实例化对象
#        格式:对象名(变量名)=类名(参数列表)    注意:没有参数列表小括号也不能省略


# 访问属性:
#         格式 : 对象名.属性名
#          赋值 : 对象名.属性名 =新值

per1 = person()
per1.name = "张三"
per1.age = 25
per1.height = 165
per1.weight = "80kg"

print(per1.name, per1.age, per1.height, per1.weight)  # 张三 25 165 80kg

# 访问方法:
#       格式: 对象名.方法名(参数列表)
per1.openDoor()
per1.filEle()
per1.closeDoor()
# 我已经打开了冰箱门
# 我已经把大象装进了冰箱了哈哈哈
# 我已经关闭了冰箱门
# 创建一个简单的类
class person(object):
    # 实例化对象
    name = ""
    age = 1000000000
    height = 0
    weight = 0
    # 定义方法(定义函数)
    # 注意: 方法参数必须self 当第一个参数
    # self 代表类的实例(某个对象)

    def run(self):
        print("run")

    def eat(self, food):
        print("eat--" + food)

    def openDoor(self):
        print("我已经打开了冰箱门")

    def filEle(self):
        print("我已经把大象装进了冰箱了哈哈哈")

    def closeDoor(self):
        print("我已经关闭了冰箱门")


# 实例化对象
#        格式:对象名(变量名)=类名(参数列表)    注意:没有参数列表小括号也不能省略
# 访问属性:

#         格式 : 对象名.属性名
#          赋值 : 对象名.属性名 =新值

per1 = person()

per1.name = "张三"
per1.age = 25
per1.height = 165
per1.weight = "80kg"
print(per1.name, per1.age, per1.height, per1.weight)  # 张三 25 165 80kg

# 访问方法:
#       格式: 对象名.方法名(参数列表)
per1.openDoor()
per1.filEle()
per1.closeDoor()

# 我已经打开了冰箱门
# 我已经把大象装进了冰箱了哈哈哈
# 我已经关闭了冰箱门


per1.eat("苹果")
# eat--苹果
# 目前来看person创建的所有对象属性都是一样的  不符合逻辑常理
#  对象没有一模一样的
per2 = person()
print(per2.age)
per3 = person()
print(per3.age)
# 1000000000
# 1000000000
class Stud(object):
    a="lover"
    n="哈哈哈哈哈"
    def __init__(self,name,age,sex):
        self.name=name
        self.age=age
        self.sex=sex
    def aa(self,man):
        print(self.a,"------------------------->这是类类属性")
        print(self.name,"---------->>这是实例化属性")
        print("啦啦啦啦啦啦啦啦啦啦",man)
    def bb(self):
        print("我是猪!!!!!!!!!!!!!!!!!11")

# 类 了解
st=Stud("李四",22,"")
p=st.a    # lover
d=st.n    # 哈哈哈哈哈
print(p)  # lover ------------------------->这是类类属性
print(d)  # 李四 ---------->>这是实例化属性
print("******************************")
st.aa("儿-------------子")                  #  啦啦啦啦啦啦啦啦啦啦 儿-------------子
print("******************************")
print(st.__dict__)                          # {'name': '李四', 'age': 22, 'sex': '男'}
st.__dict__["name"]="马云爸爸"
print(st.name)                              # 马云爸爸
print("******************************")
st.name="马化腾哈哈哈哈哈啊哈"
print(st.__dict__)                         # {'name': '马化腾哈哈哈哈哈啊哈', 'age': 22, 'sex': '男'}
# 狗的特点
dog={
    'name':'大黄',
    'gender':'',
    'type':'二哈'
}

dog1={
    'name':'傻逼',
    'gender':'',
    'type':'土狗'
}
# 人的特点
person1={
    'name':'张三丰',
    'gender':'',
    'type':''
}

# 狗的动作行为
def jiao (aa):
    print('一条狗[%s],会叫汪汪'%aa['name'])
      # 一条狗[大黄],会叫汪汪

def chi(aa):
    print('一条狗[%s]会吃屎'%aa['type'])
    # 一条狗[二哈]会吃屎
jiao(dog)
chi(dog)
chi(dog1)
jiao(person1)
# 一条狗[大黄],会叫汪汪
# 一条狗[二哈]会吃屎
# 一条狗[土狗]会吃屎
# 一条狗[张三丰],会叫汪汪
# 练习一:在终端输出如下信息

# 小明,10岁,男,上山去砍柴
# 小明,10岁,男,开车去东北
# 小明,10岁,男,最爱大保健

# 老李,90岁,男,上山去砍柴
# 老李,90岁,男,开车去东北
# 老李,90岁,男,最爱大保

class Foo:
    def __init__(self, name, age ,gender):
        self.name = name
        self.age = age
        self.gender = gender
    def kanchai(self):
        print "%s,%s岁,%s,上山砍柴" %(self.name, self.age, self.gender)
    def qudongbei(self):
        print "%s,%s岁,%s,开车去东北" %(self.name, self.age, self.gender)
    def dabaojian(self):
        print "%s,%s岁,%s,最爱大保健" %(self.name, self.age, self.gender)
xiaoming = Foo('小明', 10, '')
print(xiaoming)
xiaoming.kanchai()
xiaoming.qudongbei()
xiaoming.dabaojian()
练习二:游戏人生程序

1、创建三个游戏人物,分别是:
苍井井,女,18,初始战斗力1000
东尼木木,男,20,初始战斗力1800
波多多,女,19,初始战斗力2500
2、游戏场景,分别:
草丛战斗,消耗200战斗力
自我修炼,增长100战斗力
多人游戏,消耗500战斗力


# -*- coding:utf-8 -*-
# #####################  定义实现功能的类  #####################
class Person:
    def __init__(self, na, gen, age, fig):
        self.name = na
        self.gender = gen
        self.age = age
        self.fight =fig
    def grassland(self):
        """注释:草丛战斗,消耗200战斗力"""
        self.fight = self.fight - 200
    def practice(self):
        """注释:自我修炼,增长100战斗力"""
        self.fight = self.fight + 200
    def incest(self):
        """注释:多人游戏,消耗500战斗力"""
        self.fight = self.fight - 500
    def detail(self):
        """注释:当前对象的详细情况"""
        temp = "姓名:%s ; 性别:%s ; 年龄:%s ; 战斗力:%s"  % (self.name, self.gender, self.age, self.fight)
        print temp
# #####################  开始游戏  #####################
cang = Person('苍井井', '', 18, 1000)    # 创建苍井井角色
dong = Person('东尼木木', '', 20, 1800)  # 创建东尼木木角色
bo = Person('波多多', '', 19, 2500)      # 创建波多多角色
 
cang.incest() #苍井空参加一次多人游戏
dong.practice()#东尼木木自我修炼了一次
bo.grassland() #波多多参加一次草丛战斗
 
 
#输出当前所有人的详细情况
cang.detail()
dong.detail()
bo.detail()
 
 
cang.incest() #苍井空又参加一次多人游戏
dong.incest() #东尼木木也参加了一个多人游戏
bo.practice() #波多多自我修炼了一次
 
#输出当前所有人的详细情况
cang.detail()
dong.detail()
bo.detail()
# 游戏人生
# 类:把一类事务的相同的特点和动作整合到一起就是类 类是一个抽象的概念
# 对象: 就是基于类而创建的一个具体的事物 也是特点动作整合一起

# 学习类:
#     特点 : name addr type
#     动作 : 考试  招生   开除学生


def shcool(name,addr,type):
    def kao_shi(school):
          print("%s学校正在考试"%school["name"])
    def zhao_sheng(school):
          print("%s %s学校正在考试"%(school["type"],school["name"]))
    sch={
      "name":name,
      "addr":addr,
      "type" :type,
      "kao_shi":kao_shi,
      "zhao_sheng":zhao_sheng,
    }
    return sch
a1=shcool("新东方","上海","公办学校")
print(a1)
# {'name': '新东方', 'addr': '上海', 'type': '公办学校', 'kao_shi': <function shcool.<locals>.kao_shi at 0x0000023B6B3DB9D8>, 'zhao_sheng': <function shcool.<locals>.zhao_sheng at 0

print(a1["name"])        # 新东方
print(a1["kao_shi"])     # <function shcool.<locals>.kao_shi at 0x000001DBCED8B9D8>
print(a1["zhao_sheng"])  # <function shcool.<locals>.kao_shi at 0x000001DBCED8B9D8>

a1["kao_shi"](a1)        # 新东方学校正在考试
a1["zhao_sheng"](a1)     # 公办学校 新东方学校正在考试
# 类:把一类事务的相同的特点和动作整合到一起就是类 类是一个抽象的概念
# 对象: 就是基于类而创建的一个具体的事物 也是特点动作整合一起

# 学习类:
#     特点 : name addr type
#     动作 : 考试  招生   开除学生

def shcool(name ,addr ,type):
    def kao_shi(school):
        print("%s学校正在考试 " %school["name"])
    def zhao_sheng(school):
        print("%s %s学校正在考试 " %(school["type"] ,school["name"]))
    def  init(name ,addr ,type):
        sch ={
            "name" :name,
            "addr" :addr,
            "type" :type,
            "kao_shi": kao_shi,
            "zhao_sheng": zhao_sheng,
        }
        return sch
    return init(name, addr, type)

a1 = shcool("新东方", "上海", "公办学校")
print(a1)
# {'name': '新东方', 'addr': '上海', 'type': '公办学校', 'kao_shi': <function shcool.<locals>.kao_shi at 0x0000023B6B3DB9D8>, 'zhao_sheng': <function shcool.<locals>.zhao_sheng at 0
print(a1["name"])  # 新东方
print(a1["kao_shi"])  # <function shcool.<locals>.kao_shi at 0x000001DBCED8B9D8>
print(a1["zhao_sheng"])  # <function shcool.<locals>.kao_shi at 0x000001DBCED8B9D8>
a1["kao_shi"](a1)  # 新东方学校正在考试
a1["zhao_sheng"](a1)  # 公办学校 新东方学校正在考试

1.构造函数 __init__()

# 创建一个简单的类
class person(object):
    # 实例化对象
    name = ""
    age = 1000000000
    height = 0
    weight = 0
    # 定义方法(定义函数)
    # 注意: 方法参数必须self 当第一个参数
    # self 代表类的实例(某个对象)
    def run(self):
        print("run")

    def eat(self, food):
        print("eat--" + food)

    def __init__(self):
        print("这里是构造函数")

# 构造函数: __int__() 在使用类创建对象的时候自动调用
# 注意: 如果不显示的写出构造函数 默认会自动添加一个空的构造函数
per1 = person()  # 这里是构造函数
# 创建一个简单的类
class person(object):
    # 实例化对象
    name = "111"
    age = 1000000000
    height = 0
    weight = 0
    # 定义方法(定义函数)
    # 注意: 方法参数必须self 当第一个参数
    # self 代表类的实例(某个对象)
    def run(self):
        print("run")

    def eat(self, food):
        print("eat--" + food)

    def __init__(self, name, age, height, weight):
        print(name, age, height, weight)
        print("这里是构造函数")


# 构造函数: __int__() 在使用类创建对象的时候自动调用
# 注意: 如果不显示的写出构造函数 默认会自动添加一个空的构造函数
# self  代表当前对象


per1 = person("张三", 20, 170, "65kg")
# 张三 20 170 65kg
# 这里是构造函数
# print("***********************************")
print(per1)
print(per1.name)
# <__main__.person object at 0x00000233202F3C18>
# 111
# 类 的命名空间
class Als(object):
    n="lover----"
    def __init__(self,name,age,sex):
        self.name=name
        self.age=age
        self.sex=sex
    def aa(self):
        print("11111111111111111111111")

print(Als.__dict__) # {'__module__': '__main__', 'n': 'lover----', '__init__': <function Als.__init__ at 0x000001DB86B0EC80>, 'aa': <function Als.aa at 0x000001DB86B0ED08>, '__dict__': <attribute '__dict__' of 'Als' objects>, '__weakref__': <attribute '__weakref__' of 'Als' objects>, '__doc__': None}

print("***************************")
v=Als("张三",100,"")
d=Als("李四",10,"")
print(v.n)  # lover----
v.n="哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈"
print("***************************")
print(v.name)  # 张三
print("***************************")
print(d.n)  # lover----
# 类属性 可以通过 类来调用 也可以通过 对象调用
v.n="哈哈哈哈"
print(v.n)  # 哈哈哈哈
print(v.__dict__)   # {'name': '张三', 'age': 100, 'sex': '男', 'n': '哈哈哈哈'}
print("***************************")
print(Als.__dict__)   #
print(d.__dict__)                             #  {'name': '李四', 'age': 10, 'sex': '女'}
print(v.__dict__)   #是在实例化对象创建一个    #   {'name': '张三', 'age': 100, 'sex': '男', 'n': '哈哈哈哈'}
print("*************qqqqqqqqqqqqqq**************")
print(v.aa())   #11111111111111111111111
print("***************************")
print(d.aa())
print(v.name)  # 张三
print(d.name)  # 李四




class Da(object):
name="张三"
def __init__(self,name):
self.name=name

cc=Da("李四")
print(Da.name) #张三
print(cc.name) # 李四
cc.name="王五哈哈哈"
print(cc.name) # 王五哈哈哈
print(Da.name) # 通过 类直接访问 对象对象属性
print(cc.name) # 王五哈哈哈

print("*******************************************************8")
bb=Da("啊哈哈哈哈")
print(bb.name) # 王五哈哈哈
print(Da.name) # 张三
 
# 创建一个简单的类
class person(object):

  # 实例化对象
       name=""
       age=1000000000
       height=0
       weight=0

       # 定义方法(定义函数)
       # 注意: 方法参数必须self 当第一个参数
       # self 代表类的实例(某个对象)
       
       def run(self):
          print("run")

       def eat(self,food):
         print("eat--"+food)

       def __init__(self,name,age,height,weight):
        # 定义属性       
         self.name=name
         self.age=age
         self.height=height
         self.weight=weight

# 使用构造函数创建出来的每个对象是不一样的

# 构造函数: __int__() 在使用类创建对象的时候自动调用
# 注意: 如果不显示的写出构造函数 默认会自动添加一个空的构造函数

# self  代表当前对象

per1=person("张三",20,170,"65kg") 
print(per1.name,per1.age,per1.height,per1.weight)
# 张三 20 170 65kg

per2=person("李四",2000,170000,"650000000kg")  
print(per2.name,per2.age,per2.height,per2.weight)
# 李四 2000 170000 650000000kg

 2. self代表类的实例 

# self 代表类的实例     而非类
# # 那个对象调用的方法 name该方法中的self 就代表那个对象
# self.__class__   :代表类名
# 注意self 不是python中 的关键字
# 创建一个简单的类
class person(object):
    # 定义方法(定义函数)
    # 注意: 方法参数必须self 当第一个参数
    # self 代表类的实例(某个对象)
    def run(self):
        print("run")

    def eat(self, food):
        print("eat--" + food)

    def say(self):
        print(self.name, self.age, self.height, self.weight)

    def play(aa):
        print("注意self不是关键字换成其他的标志符也是可以的")

    def __init__(self, name, age, height, weight):
        # 定义属性
        self.name = name
        self.age = age
        self.height = height
        self.weight = weight

# 使用构造函数创建出来的每个对象是不一样的
per1 = person("李四", 20, 160, 80)
per1.say()  # 李四 20 160 80
per2 = person("张三丰", 20000, 1600000, 80000)
per2.say()  # 张三丰 20000 1600000 80000
per2.play()  # 注意self不是关键字
# self 代表类的实例     而非类


# # 那个对象调用的方法 name该方法中的self 就代表那个对象


# self.__class__   :代表类名


# 创建一个简单的类
class person(object):
    # 定义方法(定义函数)
    # 注意: 方法参数必须self 当第一个参数
    # self 代表类的实例(某个对象)

    def run(self):
        print("run")

    def eat(self, food):
        print("eat--" + food)

    def say(self):
        print(self.name, self.age, self.height, self.weight)
        print(self.__class__)  # <class '__main__.person'>

    def __init__(self, name, age, height, weight):
        # 定义属性
        self.name = name
        self.age = age
        self.height = height
        self.weight = weight

# 使用构造函数创建出来的每个对象是不一样的
per1 = person("李四", 20, 160, 80)
per1.say()  # 李四 20 160 80

per2 = person("张三丰", 20000, 1600000, 80000)
per2.say()  # 张三丰 20000 1600000 80000
# self 代表类的实例     而非类
# # 那个对象调用的方法 name该方法中的self 就代表那个对象
# self.__class__   :代表类名

# 创建一个简单的类
class person(object):
       # 定义方法(定义函数)
       # 注意: 方法参数必须self 当第一个参数
       # self 代表类的实例(某个对象)
       
       def run(self):
          print("run")

       def eat(self,food):
         print("eat--"+food)

       def say(self):
         print(self.name ,self.age ,self.height ,self.weight)
         print(self.__class__)    #<class '__main__.person'>
      
       def __init__(self,name,age,height,weight):
        # 定义属性       
         self.name=name
         self.age=age
         self.height=height
         self.weight=weight

# 使用构造函数创建出来的每个对象是不一样的
per1=person("李四",20,160,80)   
per1.say()    #李四 20 160 80

per2=person("张三丰",20000,1600000,80000)
per2.say()      #张三丰 20000 1600000 80000
class Aa(object):
    ne="1111"
    def __init__(self,name,age):
        self.name = name
        self.age=age

    def aa(self):
        print("哈哈哈哈")
        print(self.ne)
        print(self.__class__)

    def bb(self):
        print("啦啦啦啦啦啦")
        print(self.__class__)


cc=Aa("张三",1444)
bb=Aa("李四",222)
print(bb.__dict__)
print(cc.__dict__)
cc.aa()
bb.aa()
原文地址:https://www.cnblogs.com/Sup-to/p/10872890.html