Python面向对象编程基础
面向对象编程是Python核心编程之一,面向对象是一种编程思想。每个类别都有自己的特征与行为,而类就是描述这些具有相同属性与方法的对象的集合。通过下图我们可以全面了解面向对象基本概念:
一、基本概念
-
类的属性:类具有的特征,对于人类来说,身高、体重、性别等是基本属性。
-
类的方法:类具有的功能,对于人来来说,吃饭、睡觉、工作等是通用方法。
-
类的实例:类对应的一个具体对象,比如梅西,詹姆斯都是实际存在的人;每个实例都有自己实际属性与方法,比如詹姆斯的姓名,体重等。
-
对象的方法:对象行为的描述,对于人类来说,吃饭,睡觉,工作都是方法。
二、定义类
class Person: pass
三、添加类的属性
人类有的公共属性,例如居住在地球,氧气和水是必需品;我们可以将其添加到类中:
class Person: place = 'earth' need_list = ['water','food','oxygen'] #我们可以直接访问这些属性 print(Person.place) print(Person.need_list)

四、添加类的方法
class Person: place = 'earth' need_list = ['water','food','oxygen'] def eat(self, food_list): print("I eat:", food_list) def sleep(self): print("I sleep at 23:00") def work(self, work_task): print("My work task is ", work_task) def say(self, what): print("I want to say:", what)
五、类的实例化
class Person: place = 'earth' need_list = ['water','food','oxygen'] def eat(self, food_list): print("I eat:", food_list) def sleep(self): print("I sleep at 23:00") def work(self, work_task): print("My work task is ", work_task) def say(self, what): print("I want to say:", what) p1 = Person() p2 = Person() p1.sleep() p2.sleep() Person.sleep(p1)
六、重要的__init__方法
人有名称,年龄等自己特征,如何在实例化时候指定这些属性,这里我们需要使用__init__方法,我们先来添加一个__init__方法,看一下调用过程。
class Person: place = 'earth' need_list = ['water','food','oxygen'] def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex p1 = Person("Taolin", "34", "man") p2 = Person("ChenSan", "33", "woman") print(p1.name, p1.age, p1.sex) print(p2.name, p2.age, p2.sex)
七、类属性与实例属性
class Person: place = 'earth' need_list = ['water','food','oxygen'] def __init__(self, name, age, sex): self.name = name self.age = age self.sex = sex p1 = Person("Taolin", "34", "man") p2 = Person("ChenSan", "33", "woman") print(p1.place) print(p2.place) print(Person.place) print("----------------------------") p1.place='Anhui' p2.place='Jiangsun' print(p1.place) print(p2.place) print(Person.place)

print(Person.__dict__) print(p1.__dict__)
D:\Python37\python.exe E:/python_project/pymysql_test.py {'__module__': '__main__', 'place': 'earth', 'need_list': ['water', 'food', 'oxygen'], '__init__': <function Person.__init__ at 0x00BD86A8>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None} {'name': 'Taolin', 'age': '34', 'sex': 'man'}


浙公网安备 33010602011771号