python 面向对象笔记
2013-02-26 17:03
405 查看
一、类属性VS实例属性
类属性和实例属性都可以动态的创建!
1、访问类属性
类属性可以通过类或者实例来进行访问,但是类属性不能通过实例来进行更新。当通过实例对类属性进行更新时,会在实例中创建一个实例属性。
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
a classmethod, returns an instance of the subclass when called on a subclass:
classmethod能够访问类属性,但是staticmethod则不能。
类属性和实例属性都可以动态的创建!
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则不能。
相关文章推荐
- Python3.X之面向对象高级编程笔记
- Dive into python 第5和6章面向对象学习笔记
- 【Python】学习笔记——-8.1、面向对象高级编程:1.使用__slots__
- python笔记11--面向对象
- python学习笔记——6_面向对象
- 【Python】学习笔记九:面向对象拓展
- [Python学习笔记][第六章Python面向对象程序设计]
- 初学Python的学习笔记9----面向对象编程(获取对象信息、实例属性和类属性)、面向对象高级编程(使用__slots__、使用@property)
- python面向对象笔记
- 【Python】学习笔记——-8.2、面向对象高级编程:2.使用@property
- python 学习笔记--面向对象
- python2.7学习笔记(10) ——面向对象高级编程
- Python面向对象学习笔记-类、属性、方法
- Python面向对象高级编程——学习笔记
- DAY6之Python学习笔记:面向对象术语整理
- [Python学习笔记][第六章Python面向对象程序设计]
- 【Python】学习笔记——-8.3、面向对象高级编程:3.多重继承
- Python学习笔记 - 面向对象高级编程
- 廖雪峰python学习笔记8:面向对象初步
- Python3 高级功能学习笔记(面向对象和正则表达式)