python 面向对象笔记

一、类属性VS实例属性

类属性和实例属性都可以动态的创建!

1、访问类属性

类属性可以通过类或者实例来进行访问,但是类属性不能通过实例来进行更新。当通过实例对类属性进行更新时,会在实例中创建一个实例属性。

class MyClass(object):
    version = 1.0
c = MyClass()
print(MyClass.version)
print(c.version)
MyClass.version = 1.1
c.version = 1.5 #这里不会更改类属性,而是创建一个实例属性
print(MyClass.version)
print(c.version)
输出:

1.0
1.0
1.1
1.5

2、从实例中访问类属性需谨慎

任何对实例属性的赋值都会创建一个实例属性(如果不存在该实例属性)并且对它赋值。因为python中的实例是可以动态的添加属性的。

二、static method VS class method

A staticmethod is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument. It is basically useless in Python -- you can just use a module function instead of a staticmethod.

A classmethod, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. This is useful when you want the method to be a factory for the class: since it gets the actual class it was called on as first argument, you can always instantiate the right class, even when subclasses are involved. Observe for instance how dict.fromkeys(), a classmethod, returns an instance of the subclass when called on a subclass:

classmethod能够访问类属性,但是staticmethod则不能。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值