面向对象(类与对象)

类与对象

  • 在现实世界中:肯定是先有对象,再有类
世界上肯定是先出现各种各样的实际存在的物体,然后随着人类文明的发展,人类站在不同的角度总结出了不同的种类,比如
人类、动物类、植物类等概念。也就说,对象是具体的存在,而类仅仅只是一个概念,并不真实存在,比如你无法告诉我人类
具体指的是哪一个人
  • 在程序中:务必保证先定义类,后产生对象
这与函数的使用是类似的:先定义函数,后调用函数,类也是一样的:在程序中需要先定义类,后调用类。不一样的是:调用
函数会执行函数体代码返回的是函数体执行的结果,而调用类会产生对象,返回的是对象

定义类

按照上述步骤,我们来定义一个类

#在Python中程序中的类用class关键字定义,而在程序中特征用变量标识,技能用函数标识,因而类中最常见的无非是:变量和函数的定义
class LuffyStudent:
    school='luffy'
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def learn(self):
        print('is learning')

    def eat(self):
        print('%s is eating' %self.name)

    def sleep(self):
        print('%s is sleeping' %self.name)

    def __del__(self):
        print("running del method, this person must be died.")

# 后产生对象
stu1=LuffyStudent('alex',18)
stu2=LuffyStudent('li',28)
stu3=LuffyStudent('hy',38)
print(LuffyStudent.__dict__)

stu1.eat()
stu2.eat()
stu3.sleep()


print('--end program--')

输出结果

{'__module__': '__main__', 'school': 'luffy', '__init__': <function LuffyStudent.__init__ at 0x00000000028CB8C8>, 'learn': <function LuffyStudent.learn at 0x000000001272FB70>,
'eat': <function LuffyStudent.eat at 0x000000001272FBF8>, 'sleep': <function LuffyStudent.sleep at 0x000000001272FC80>, '__del__': <function LuffyStudent.__del__ at 0x000000001272FD08>,
'__dict__': <attribute '__dict__' of 'LuffyStudent' objects>, '__weakref__': <attribute '__weakref__' of 'LuffyStudent' objects>, '__doc__': None} alex is eating li is eating hy is sleeping --end program-- running del method, this person must be died. running del method, this person must be died. running del method, this person must be died.

注意:

  • 类中可以有任意python代码,这些代码在类定义阶段便会执行,因而会产生新的名称空间,用来存放类的变量名与函数名,可以通过LuffyStudent.__dict__查看
  • 类中定义的名字,都是类的属性,点是访问属性的语法。
  • 对于经典类来说我们可以通过该字典操作类名称空间的名字,但新式类有限制(新式类与经典类的区别我们将在后续章节介绍)

类的使用

print(LuffyStudent.school)  # 查
# luffy
LuffyStudent.school='Oldboy' # 改
print(LuffyStudent.school)  # 查
# Oldboy
LuffyStudent.sex='male' # 增
print(LuffyStudent.sex)
# male 
del LuffyStudent.sex # 删
print('--end program--')

对象的使用

#执行__init__,stu1.name='alex',
# 很明显也会产生对象的名称空间可以用stu1.__dict__查看,查看结果为
print(stu1.__dict__)

print(stu1.name) #查,等同于stu1.__dict__['name']
stu1.name='王三炮' #改,等同于stu1.__dict__['name']='王三炮'
print(stu1.__dict__)
stu2.course='python' #增,等同于stu1.__dict__['course']='python'
print(stu2.__dict__)
del stu2.course #删,等同于stu2.__dict__.pop('course')
print(stu2.__dict__)

#输出结果:

alex
{'name': '王三炮', 'age': 18}
{'name': 'li', 'age': 28, 'course': 'python'}
{'name': 'li', 'age': 28}

补充说明

  • 站的角度不同,定义出的类是截然不同的;
  • 现实中的类并不完全等于程序中的类,比如现实中的公司类,在程序中有时需要拆分成部门类,业务类等;
  • 有时为了编程需求,程序中也可能会定义现实中不存在的类,比如策略类,现实中并不存在,但是在程序中却是一个很常见的类。
 
原文地址:https://www.cnblogs.com/xiao-apple36/p/9127525.html