【python】面向对象-类

1. 类属性,实例属性

>>> class MC:

        x = 0

        z = {1:1}

        def __init__(self):

            self.y = 1

>>> mc1 = MC()

>>> mc2 = MC()

 

// 可以通过类名或实例名来访问类属性

>>> mc1.x, mc2.x, MC.x

>>> (0, 0, 0)

 

// 不能通过类名来访问实例属性

>>> mc1.y, mc2.y

>>> (1, 1)

>>> MC.y

>>> class MC has no attribute 'y'

 

// 实例赋值操作会产生同名实例属性,并遮蔽类属性

>>> mc1.x += 1

>>> mc1.x, mc2.x, MC.x

>>> (1, 0, 0)

>>> del mc1.x

>>> mc1.x, mc2.x, MC.x

>>> (0, 0, 0)

// 当类属性是可变变量时,会出现下面现象

// 此时没有产生实例属性

>>> mc1.z[2]=2

>>> mc1.z 

>>> mc1.x, mc2.x, MC.x

>>> ({1:1,2:2},{1:1,2:2},{1:1,2:2})

 

// 类属性的修改应使用类名,而不是属性名

>>> MC.x += 1

>>> mc1.x, mc2.x, MC.x

>>> (1, 1, 1)

 

2. 实例方法,类方法,静态方法

class A(object):

    # 类实例方法

    def foo(self, x):

        print "executing foo(%s,%s)" % (self, x)

    

    # 类方法

    @classmethod

    def class_foo(cls, x):

        print "executing class_foo(%s,%s)" % (cls, x)

    

    # 静态方法

    @staticmethod

    def static_foo(x):

        print "executing static_foo(%s)" % (x)

 

>>> a = A()

>>> a.foo(1)

executing foo(<__main__.A object at 0x02A8C210>,1)

>>> a.class_foo(1)

executing class_foo(<class '__main__.A'>,1)

>>> A.class_foo(1)

executing class_foo(<class '__main__.A'>,1)

>>> a.static_foo(1)

executing static_foo(1)

>>> A.static_foo(1)

executing static_foo(1)

 

  • 类方法和静态方法都可以被类和类实例调用,类实例方法仅可以被类实例调用
  • 类方法的隐含调用参数是类,而类实例方法的隐含调用参数是类的实例,静态方法没有隐含调用参数
  • 实例方法可以访问实例属性和类属性,类方法可以访问类属性,静态方法两者都不能访问
  • 类方法更像是C++/java中静态方法, 而静态方法像是放在类名字空间中的一个函数

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值