python-33 面向对象:类和对象之一

类:把一类事物相同的特征和动作整合到一起,就是类,类是抽象的概念。

类的本质:一种数据结构

对象:基于类产生的一个具体事物,具有类的动作和特征,只包含自己的特征数据。

实例化:就是类名(),也就是初始化__init__(),它的作用就是产生一个字典,初始化结果就是返回一个实例对象。

对象.属性名:先在自己的字典里查找,如果没有,再去类的字典里查找。即有其作用域。

实例通过引用的方法去访问类的函数属性,这样节约资源

#py2中类分经典类和新式类,class A:经典类,class B(object)新式类,py3中全是新式类
country='China'
population=20000
class School: #类:数据属性+方法属性
    proper='公立'  #数据属性,又叫类的静态属性
    country='American'
    ls=[1,2,3]
    def __init__(self,name,add,tel): #只包含对象的数据属性,在对象的__dict__中
        self.name=name,
        self.add=add,
        self.tel=tel
        print('--->',country)#返回:---> China,表示查找变量country,全局找,返顺'China',s.country或School.country,则是查属性'American'

    def test(self): #类的方法属性
        print('%s正在举行考试。。。'%self.name)
    def enrollment(self):
        print('%s正在招生。。。'%self.name)
s1=School('中国科技大学','合肥','05511114556')
s2=School('清华大学','北京','010111222')
s1.test()
s2.enrollment()
print(School)#<class '__main__.School'>,__main__下的School类
print(s1)#<__main__.School object at 0x004EFA50>,__main__下School类的对象地址
print(School.__dict__) #'__module__': '__main__', 'proper': '公立', '__init__': <function School.__init__ at 0x015BC6A8>, 'test': <function School.test at 0x01C9E8A0>, 'enrollment': <function School.enrollment at 0x01C9E858>, '__dict__': <attribute '__dict__' of 'School' objects>, '__weakref__': <attribute '__weakref__' of 'School' objects>, '__doc__': None}
#School.__dict__,查看类的属性字典,包含类的数据属性和方法属性
print(s1.__dict__)#{'name': ('中国科技大学',), 'add': ('合肥',), 'tel': '05511114556'},仅包含实例化对象的数据属性

#=类属性:增删查改===================
s1.order='NO1'
School.area=500#增加
print(s1.order,School.area)#NO1 500
s1.area=600 #更改
print(s1.area,School.area)#600 500,查看
s2.ls=['a','b']#这是给s2增一个ls的列表属性,不影响School的ls列表
print(School.ls)#[1, 2, 3]
s1.ls.append('a')#这是引用了School.ls列表,给School.ls列表增加一个元素'a',s1中没有增加列表
print(s1.__dict__)#没有ls属性,{'name': ('中国科技大学',), 'add': ('合肥',), 'tel': '05511114556', 'order': 'NO1', 'area': 600}
print(School.ls)#School.ls列表改变,[1, 2, 3, 'a']

del s1.order#删除
print(s1.population)#报错,仅管有个全局变量population=20000,类的查找顺序是:实例字典,再到类字典,没有就报错
#注:print('--->',country),是在查找变量country,而s1.population表示查找s1对象属性'population',是两回事,查属性在字典里找,查变量在全局找
View Code
原文地址:https://www.cnblogs.com/Zhouzg-2018/p/10278045.html