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

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

类的本质:一种数据结构

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

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

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

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

#py2中类分经典类和新式类,class A:经典类,class B(object)新式类,py3中全是新式类
class School: #类:数据属性+方法属性
    proper='公立'  #数据属性
    def __init__(self,name,add,tel): #只包含对象的数据属性,在对象的__dict__中
        self.name=name,
        self.add=add,
        self.tel=tel
    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'},仅包含实例化对象的数据属性
View Code

猜你喜欢

转载自www.cnblogs.com/Zhouzg-2018/p/10278045.html
今日推荐