1 class definition 语法:
#!/usr/bin/python
class Employee:
emCount=0;
def __init__ (self ,name,salary) :
self.name = name
self.salary = salary
Employee.emCount +=1;
def display(self):
print ("Total Employee %d" % Employee.empCount)
def displayCount(self):
print ("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print ("Name : ", self.name, ", Salary: ", self.salary)
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
几点需要注意的:
-
The first method __init__() is a special method which is called class constructor or initialization method that Python calls when you create a new instance of this class.
-
You declare other class methods like normal functions with the exception that the first argument to each method is self . Python adds the self argument to the list for you ; you don't need to include it when you call the methods.
Python Class 定义比较特别的地方:
Python 的 Class 比较特别,和我们习惯的静态语言类型定义有很大区别。
1. 使用一个名为 __init__ 的方法来完成初始化。
2. 使用一个名为 __del__ 的方法来完成类似析购操作。
3. 所有的实例方法都拥有一个 self 参数来传递当前实例,类似于 this。
4. 可以使用 __class__ 来访问类型成员。
Instead of using the normal statements to access attributes, you can use following functions:
-
The getattr(obj, name[, default]) : to access the attribute of object.
-
The hasattr(obj,name) : to check if an attribute exists or not.
-
The setattr(obj,name,value) : to set an attribute. If attribute does not exist then it would be created.
-
The delattr(obj, name) : to delete an attribute.
class的一些内在属性:
-
__dict__ : Dictionary containing the class's namespace.
-
__doc__ : Class documentation string, or None if undefined.
-
__name__: Class name.
-
__module__: Module name in which the class is defined. This attribute is "__main__" in interactive mode.
-
__bases__ : A possibly empty tuple containing the base classes, in the order of their occurrence in the base class list.
往类中添加类变量:
类名.属性名
such as testClass.name;
给对象添加属性:给对象添加的属性仅仅属于改对象;
对象名.属性名;
Destory class :
一般来说python 的garbige 收集器会自动收集
Python's garbage collector runs during program execution and is triggered when an object's reference count reaches zero.
如果你想自己回收或者删除一个class,你也可以通过重载__del__ 方法来实现。
2python中类的继承:
class SubClassName (ParentClass1[, ParentClass2, ...]):
'Optional class documentation string'
class_suite
多继承的语法:
class A: # define your class A
.....
class B: # define your calss B
.....
class C(A, B): # subclass of A and B
关于多继承的一些解释:
9.5.1 多继承 Multiple Inheritance
Python supports a limited form of multiple inheritance as well. A class definition with multiple base classes looks as follows:
Python同样有限的支持多继承形式。多继承的类定义形如下例:
class DerivedClassName(Base1, Base2, Base3):
<statement-1>
.
.
.
<statement-N>
The only rule necessary to explain the semantics is the resolution rule used for class attribute references. This is depth-first, left-to-right. Thus, if an attribute is not found in DerivedClassName , it is searched in Base1 , then (recursively) in the base classes of Base1 , and only if it is not found there, it is searched in Base2 , and so on.
这里唯一需要解释的语义是解析类属性的规则。顺序是深度优先,从左到右。因此,如果在 DerivedClassName (示例中的派生类)中没有找到某个属性,就会搜索 Base1 ,然后(递归的)搜索其基类,如果最终没有找到,就搜索 Base2 ,以此类推。
(To some people breadth first -- searching Base2 and Base3 before the base classes of Base1 -- looks more natural. However, this would require you to know whether a particular attribute of Base1 is actually defined in Base1 or in one of its base classes before you can figure out the consequences of a name conflict with an attribute of Base2 . The depth-first rule makes no differences between direct and inherited attributes of Base1 .)
(有些人认为广度优先--在搜索Base1 的基类之前搜索Base2 和Base3
--看起来更为自然。然而,如果Base1 和Base2 之间发生了命名冲突,你需要了解这个属性是定义于Base1 还是Base1 的基类中。而深度优先不区分属性继承自基类还是直接定义。)
It is clear that indiscriminate use of multiple inheritance is a maintenance nightmare, given the reliance in Python on conventions to avoid accidental name conflicts. A well-known problem with multiple inheritance is a class derived from two classes that happen to have a common base class. While it is easy enough to figure out what happens in this case (the instance will have a single copy of ``instance variables'' or data attributes used by the common base class), it is not clear that these semantics are in any way useful.
显然不加限制的使用多继承会带来维护上的噩梦,因为 Python 中只依靠约定来避免命名冲突。多继承一个很有名的问题是派生继承的两个基类都是从同一个基类继承而来。目前还不清楚这在语义上有什么意义,然而很容易想到 这会造成什么后果(实例会有一个独立的“实例变量”或数据属性复本作用于公共基类。)
You can use issubclass() or isinstance() functions to check a relationships of two classes and instances:
-
The issubclass(sub, sup) boolean function returns true if the given subclass sub is indeed a subclass of the superclass sup .
-
The isinstance(obj, Class) boolean function returns true if obj is an instance of class Class or is an instance of a subclass of Class
Python类中的私有数据:
Python中没有所谓的访问控制,如公有,私有,受保护的变量等。如果你想使得某个属性变量变为私有,可以在变量名前加 __变量名
>>> class FooCounter:
... __secretCount = 0
... def foo(self):
... self.__secretCount += 1
... print self.__secretCount
...
>>> foo =FooCounter()
>>> foo.foo()
1
>>> foo.__secretCount
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: FooCounter instance has no attribute '__secretCount'
>>> foo.FooCounter.__secretCount
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: FooCounter instance has no attribute 'FooCounter'
>>> foo._FooCounter.__secretCount
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: FooCounter instance has no attribute '_FooCounter'
>>> foo._FooCounter__secretCount
1
>>>
如果你需要访问,可以使用对象名._类名__属性名
Python中的弱引用:
"A weak reference to an object is not enough to keep the object alive: when the only remaining references to a referent are weak references, garbage collection is free to destroy the referent and reuse its memory for something else. A primary use for weak references is to implement caches or mappings holding large objects, where it’s desired that a large object not be kept alive solely because it appears in a cache or mapping.A primary use for weak references is to implement caches or mappings holding large objects, where it’s desired that a large object not be kept alive solely because it appears in a cache or mapping."
关键点是:是希望可以使用某些对象,但又不希望妨碍系统的垃圾回收
典型应用场景:大对象的缓存和映射
import weakref
Weak refrences can be ueful for creating caches of objects that are expensive to create.
Proxy objects are weak reference objects that behave like the object they reference so that you do not have to first call the weak reference to access the underlying object.
weakref.proxy(obj[,callback])
Python中的重载:overlod
Base Overloading Methods:
Following table lists some generic functionality that you can override in your own classes:
SN | Method, Description & Sample Call |
---|---|
1 | __init__ ( self [,args...] ) Constructor (with any optional arguments) Sample Call : obj = className(args) |
2 | __del__( self ) Destructor, deletes an object Sample Call : dell obj |
3 | __repr__( self ) Evaluatable string representation Sample Call : repr(obj) |
4 | __str__( self ) Printable string representation Sample Call : str(obj) |
5 | __cmp__ ( self, x ) Object comparison Sample Call : cmp(obj, x) |
更多的overloading method 参考文档。