2018-01-10 python 面向对象

类:

属性--变量

方法--函数

类和对象

类:是对事务的抽象  球类

对象:是类的一个实例:足球

面向对象的主要思想是:

封装: 类的定义,把变量、函数组合一起 class A(object):

类的结构:

成员变量--属性

成员函数--方法

类的创建:

class MyClass(object):

def fun(self):

print "i am function"

类的方法中至少有一个参数self

class People(object):
    color='yellow'//属性  成员变量
    def think(self):  //方法
        self.color="black"
        print "i am a %s" % self.color
        print "i am thinker"

ren=People()//实例化

print ren.color
ren.think()

yellow
i am a black
i am thinker

在想访问类中的方法的时候,需要先将类实例化。

实例化就是将类赋给变量,变量就是一个对象,通过对象访问属性及方法。

类的属性

包括私有属性以及公有属性

私有属性:不能在类外及被类以外的函数调用。

定义方式:以“__”双下划线开始的成员变量就是私有属性

可以通过instance._classname__atribute方式访问。

内置属性:由系统在定义类的时候默认添加的,由前后双下划线构成,__dict__,__module__

class People(object):
    color='yellow'
    __age=30
    def think(self):
        self.color="black"
        print "i am a %s" % self.color
        print "i am thinker"
        print self.__age

ren=People()
print ren.color
ren.think()
#print ren._People__age
print ren.__dict__
print '#'*30
print People .color
ren.color='white'
print ren.color
print "*"*30
print People.__dict__
yellow
i am a black
i am thinker
30
{'color': 'black'}
##############################
yellow
white
******************************
{'__module__': '__main__', 'color': 'yellow', '__doc__': None, '__dict__': <attribute '__dict__' of 'People' objects>, '_People__age': 30, '__weakref__': <attribute '__weakref__' of 'People' objects>, 'think': <function think at 0x0000000002703B38>}

类的方法

方法的定义和函数一样,但是需要self作为第一个参数

类的方法:

公有方法:在类中和类外都可以调用

私有方法:不能被外部调用,在方法前面加上“__”双下划线就是私有方法

self 参数

用于区别函数和类的方法(必须有一个self),self参数表示执行对象本身

类方法

被classmethod()函数处理过的函数,能被类所调用,也能被对象调用(是继承关系)

静态方法

相当于“全局函数”,可以被类直接调用,可以被所有实例化对象共享,通过staticmethod()定义。 静态方法没有“self”参数

装饰器

@classmethod

@staticmethod

class People(object):
    color='yellow'
    __age=30
    def think(self):
        self.color="black"
        print "i am a %s" % self.color
        print "i am thinker"
        print self.__age
    def __talk(self):
        print "i am talking with tom"
    def test(self):
        #self.__talk()
        #print 'Tsting....'
       print  self.color
    cm=classmethod(test)
    def test1():
        print "this is func"
        print People.color
        print People.__age
    sm=staticmethod(test1)

    @classmethod
    def test2(self):
        print "this is class method "

    @staticmethod
    def test3():
        print "this is stactic method"


jack=People()
People.cm()
People.sm()
People.test2()
People.test3()



继承

多态


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值