python Object And Class
1:在Python中每一个都是对象,class 是一个对象,class的实例也是一个对象。在java或者c++中,class 是不用来存放数据的,只有class的实例才存放
数据
class class1(object):
pass
if __name__=='__main__':
test = class1()
print class1
print test
class1是一个对象,print 出来的结果:<class '__main__.class1'>
那么 test也是一个对象,test.__class__也是一个对象
2:在python中所有的对象允许动态的添加属性或者方法,当类添加属性之后,类的实例同样能够访问该对象,
如果修改了类的__class__的属性或者方法,那么该类对性的实例同样也具有该类的方法或者属性
class class1(object):
pass
if __name__=='__main__':
test = class1()
#print class1
#print test
test.__class__.newAttr=10
test1 = class1()
print test1.newAttr
当我们通过test.__class__修改了class1类的属性之后,给class1添加了个新的属性newAttr=10
则重新test = class1()新的实例后,新的实例拥有newAttr这个属性,
对于添加新的方法同样如此
3:每个实例都有__dict__来存放动态的属性,查看一下代码:
class class1(object):
pass
if __name__=='__main__':
test = class1()
#print class1
#print test
test.__class__.newAttr=10
test1 = class1()
print test.__dict__
print test.__class__.__dict__
print test1.__dict__
print test1.__class__.__dict__
test1.newAttr2=20
print test.__dict__
print test.__class__.__dict__
print test1.__dict__
print test1.__class__.__dict__
4:继承:当继承后,python不会向java,c++那样在子类的实例中包含父类的实例,子类的实例是个全新的对象,与父类一点关系都没有,
不会包含有父类的任何东西,继承只是在子类的__base__指向了父类,在查找函数,属性的过程中会查找父类,
仅此而已,而这个父类也是class对象
5:类里的变量不是以self,开头定义的都是类变量,相当于java,c++里的static,所有实例共享他们
6:python为每一个对象定义了一些属性和方法
__doc__
__module__
__class__
__bases__
__dict__
7:python的继承
基类 __init__ / __del__ 需显示调用
继承方法的调用和基类声明顺序有关
在成员名称前添加 "__" 使其成为私有成员。
除了静态(类型)字段,我们还可以定义静态方法。
class Class1:
@staticmethod
def test():
print "static method"
Class1.test()
static method
从设计的角度,或许更希望用属性(property)来代替字段(field)。
class Class1:
def __init__(self):
self.__i = 1234
def getI(self): return self.__i
def setI(self, value): self.__i = value
def delI(self): del self.__i
I = property(getI, setI, delI, "Property I")
a = Class1()
a.I
1234
a.I = 123456
a.I
123456
如果只是 readonly property,还可以用另外一种方式。
class Class1:
def __init__(self):
self.__i = 1234
@property
def I(self):
return self.__i
a = Class1()
a.I
1234
-----------------------
用 __getitem__ 和 __setitem__ 可以实现 C# 索引器的功能。
class Class1:
def __init__(self):
self.__x = ["a", "b", "c"]
def __getitem__(self, key):
return self.__x[key]
def __setitem__(self, key, value):
self.__x[key] = value
a = Class1()
a[1]
'b'
a[1] = "xxxx"
a[1]
'xxxx'
8:python的多重继承
由于python的继承主要是将几个对象建立关系,因此多重继承最重要的就是怎样在多个父类中寻找某个attribute
python寻找attribute的顺序:
1. If attrname is a Python-provided attribute for objectname, return it.
2. Check objectname.__class__.__dict__ for attrname. If it exists and is a data-descriptor, return the descriptor result. Search all bases of objectname.__class__ for the same case.
3. Check objectname.__dict__ for attrname, and return if found. Unless objectname is a type object, in which case search its bases too. If it is a type object and a descriptor is found in the object or its bases, return the descriptor result.
4. Check objectname.__class__.__dict__ for attrname. If it exists and is a non-data descriptor, return the descriptor result. If it exists, and is not a descriptor, just return it. If it exists and is a data descriptor, we shouldn't be here because we would have returned at point 2. Search all bases of objectname.__class__ for same case.
5. Raise AttributeError
9:python重载
我们还可以通过重载 __getattr__ 和 __setattr__ 来拦截对成员的访问,需要注意的是 __getattr__ 只有在访问不存在的成员时才会被调用。
>>> class Class1:
def __getattr__(self, name):
print "__getattr__"
return None
def __setattr__(self, name, value):
print "__setattr__"
self.__dict__[name] = value
>>> a = Class1()
>>> a.x
__getattr__
>>> a.x = 123
__setattr__
>>> a.x
123
如果类型继承自 object,我们可以使用 __getattribute__ 来拦截所有(包括不存在的成员)的获取操作。
注意在 __getattribute__ 中不要使用 "return self.__dict__[name]" 来返回结果,因为在访问 "self.__dict__" 时同样会被 __getattribute__ 拦截,从而造成无限递归形成死循环。
>>> class Class1(object):
def __getattribute__(self, name):
print "__getattribute__"
return object.__getattribute__(self, name)
>>> a = Class1()
>>> a.x
__getattribute__
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
a.x
File "<pyshell#1>", line 4, in __getattribute__
return object.__getattribute__(self, name)
AttributeError: 'Class1' object has no attribute 'x'
>>> a.x = 123
>>> a.x
__getattribute__
123
分享到:
相关推荐
本文实例讲述了python中metaclass原理与用法。分享给大家供大家参考,具体如下: 什么是 metaclass. metaclass (元类)就是用来创建类的类。在前面一篇文章《python动态创建类》里我们提到过,可以用如下的一个观点来...
Python:type、object、class Python: 一切为对象 >>> a = 1 >>> type(a) <class> >>> type(int) <class> type => int => 1 type => class => obj type是个类,生成的类也是对象,生成的实例是对象 >>>class ...
类和对象的概念很难去用简明的文字描述清楚。从知乎上面的一个回答中可以尝试去理解: 对象:对象是类的一个实例(对象不是找个女朋友),有状态和行为。...class student(object): def print_info
(MP3)听Python入门编程之class与object的MP3 音频文件!
class object: """ The most base type """ # del obj.xxx或delattr(obj,'xxx')时被调用,删除对象中的一个属性 def __delattr__(self, *args, **kwargs): # real signature unknown """ Implement delattr(self...
讲述Python的type, class和对象之间的关系, Python 的对象模型,翻译自Python type and object
一个python object无法直接与json转化,只能先将对象转化成dictionary,再转化成json;对json,也只能先转换成dictionary,再转化成object,通过实践,源码如下: import json class user: def __init__(self, ...
Deprecated Python modules, functions and methods asynchat asyncore dbm distutils grp importlib os re ssl tkinter venv Deprecated functions and types of the C API Deprecated Build Options ...
1.Introduction 2.Algorithm Analysis 3.Asymptotic Notation 4.Foundational Data Structures ...17.Python and Object-Oriented Programming 18.Class Hierarchy Diagrams 19.Character Codes 20.References
本文实例讲述了Python面向对象class类属性及子类用法。分享给大家供大家参考,具体如下: class类属性 class Foo(object): x=1.5 foo=Foo() print foo.x#通过实例访问类属性 >>>1.5 print Foo.x #通过类访问类属性...
这篇文章主要介绍了Python class的继承方法代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 class parent(object): def implicit(self): print(...
Stop writing scripts and start architecting programs by applying object-oriented programming techniques in Python Learn the trickier aspects of Python and put it in a structured context for deeper ...
Instead, the working projects developed in this book teach the reader how to apply their theoretical knowledge to topics such as image manipulation, augmented reality, ... and object categorization....
For each procedure, the class names, method names, and variable names are kept consistent between Java and Python examples. This way you can see clearly the differences in syntax between the two ...
Lesson 31 - Creating a class for an object type Lesson 32 - Working with your own object types Lesson 33 - Customizing classes Lesson 34 - Capstone project: card game UNIT 8 - USING LIBRARIES TO ...
用于使用 OrientDB 的 Python Object-Graph-Document-Mapper 这个项目是一个使用 RDD(自述驱动开发)过程的 META 项目。 灵感来自 基于 想法 已经有很棒的项目可以使用 Python 和 OrientDB,BulbFlow + Rexter ...
class and higher-order functions, pure functions and more, and how these are accomplished in Python to give you the core foundations you’ll build upon. After that, you’ll discover common functional ...
Functions as objects: view Python functions as first-class objects, and understand how this affects popular design patterns Object-oriented idioms: build classes by learning about references, ...