内置方法 说明
__init__(self,...) 初始化对象(实例),在创建新对象时调用
__del__(self) 析构函数,释放对象,在对象被删除之前调用,进行一些清理工作。
__new__(cls,*args,**kwd) 实例的生成操作
__str__(self) 在使用print语句输出实例时被调用
__getitem__(self,key) 获取序列的索引key对应的值,等价于seq[key]
__len__(self) 在调用内联函数len()时被调用
__cmp__(stc,dst) 比较两个对象src和dst
__getattr__(s,name) 获取属性的值
__setattr__(s,name,value) 设置属性的值
__delattr__(s,name) 删除name属性
__getattribute__() __getattribute__()功能与__getattr__()类似
__gt__(self,other) 判断self对象是否大于other对象
__lt__(slef,other) 判断self对象是否小于other对象
__ge__(slef,other) 判断self对象是否大于或者等于other对象
__le__(slef,other) 判断self对象是否小于或者等于other对象
__eq__(slef,other) 判断self对象是否等于other对象
__call__(self,*args) 把实例作为函数调用
__init__():
__init__方法在类的一个对象(实例)被建立时,马上运行。这个方法可以用来对你的对象做一些你希望的初始化。
注意,这个名称的开始和结尾都是双下划线。
Hello, my name is python
说明:__init__方法定义为取一个参数name(以及普通的参数self)。在这个__init__里,我们只是创建一个新的域,也称为name。
注意它们是两个不同的变量,尽管它们有相同的名字。点号使我们能够区分它们。最重要的是,我们没有专门调用__init__方法,
只是在创建一个类的新实例的时候,把参数包括在圆括号内跟在类名后面,从而传递给__init__方法。这是这种方法的重要之处。
现在,我们能够在我们的方法中使用self.name域。这在sayHi方法中得到了验证。
__new__():
__new__()在__init__()之前被调用,用于生成实例对象.利用这个方法和类属性的特性可以实现设计模式中的单例模式.
单例模式设计的类只能实例化一个对象。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,
从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象(实例)只能存在一个,单例模式是最好的解决方案。
None
__new__ is called!
__init__ is called!
<__main__.Singleton object at 0x029EF910>
<__main__.Singleton object at 0x029EF910>
100
__new__ is called!
__init__ is called!
<__main__.Singleton object at 0x029EF910>
<__main__.Singleton object at 0x029EF910>
200
__getattr__()、__setattr__()和__getattribute__():
当读取对象的某个属性时,python会自动调用__getattr__()方法.例如,fruit.color将转换为fruit.__getattr__(color).
当使用赋值语句对属性进行设置时,python会自动调用__setattr__()方法.
__getattribute__()的功能与__getattr__()类似,用于获取属性的值.但是__getattribute__()能提供更好的控制,代码更健壮.
注意,python中并不存在__setattribute__()方法.
代码例子:
如果类把某个属性定义为序列,可以使用__getitem__()输出序列属性中的某个元素,假设水果店中销售多钟水果,可以通过__getitem__()方法获取水果店中的某种水果。
代码例子:
['apple', 'banana']
banana
----------
banana
apple banana
---------
apple banana
__str__():
__str__()用于表示对象代表的含义,返回一个字符串.实现了__str__()方法后,可以直接使用print语句输出对象,
也可以通过函数str()触发__str__()的执行.这样就把对象和字符串关联起来,便于某些程序的实现,可以用这个字符串来表示某个类。
代码例子:
this is the class of Fruit! this is the class of Fruit!
__str__ is called!
this is the class of Fruit!
__str__ is called!
this is the class of Fruit!
__call__():
若在类中实现了__call__()方法,则该类的实例也是可调用的,调用该实例时,实际上是调用了__call__方法。使用该方法可以模拟静态方法。
代码例子:
Fruit.__init__ is called!
apple
----------
__call__ is called!
grow ...
__call__ is called!
grow ...
----------
__call__ is called!
grow ...
__init__(self,...) 初始化对象(实例),在创建新对象时调用
__del__(self) 析构函数,释放对象,在对象被删除之前调用,进行一些清理工作。
__new__(cls,*args,**kwd) 实例的生成操作
__str__(self) 在使用print语句输出实例时被调用
__getitem__(self,key) 获取序列的索引key对应的值,等价于seq[key]
__len__(self) 在调用内联函数len()时被调用
__cmp__(stc,dst) 比较两个对象src和dst
__getattr__(s,name) 获取属性的值
__setattr__(s,name,value) 设置属性的值
__delattr__(s,name) 删除name属性
__getattribute__() __getattribute__()功能与__getattr__()类似
__gt__(self,other) 判断self对象是否大于other对象
__lt__(slef,other) 判断self对象是否小于other对象
__ge__(slef,other) 判断self对象是否大于或者等于other对象
__le__(slef,other) 判断self对象是否小于或者等于other对象
__eq__(slef,other) 判断self对象是否等于other对象
__call__(self,*args) 把实例作为函数调用
__init__():
__init__方法在类的一个对象(实例)被建立时,马上运行。这个方法可以用来对你的对象做一些你希望的初始化。
注意,这个名称的开始和结尾都是双下划线。
代码例子:
class Person:
def __init__(self, name):
self.name = name
def sayHi(self):
print 'Hello, my name is', self.name
p = Person('python')
p.sayHi()
运行结果:
Hello, my name is python
说明:__init__方法定义为取一个参数name(以及普通的参数self)。在这个__init__里,我们只是创建一个新的域,也称为name。
注意它们是两个不同的变量,尽管它们有相同的名字。点号使我们能够区分它们。最重要的是,我们没有专门调用__init__方法,
只是在创建一个类的新实例的时候,把参数包括在圆括号内跟在类名后面,从而传递给__init__方法。这是这种方法的重要之处。
现在,我们能够在我们的方法中使用self.name域。这在sayHi方法中得到了验证。
__new__():
__new__()在__init__()之前被调用,用于生成实例对象.利用这个方法和类属性的特性可以实现设计模式中的单例模式.
单例模式设计的类只能实例化一个对象。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,
从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象(实例)只能存在一个,单例模式是最好的解决方案。
class Singleton(object):
__instance = None #类的私有变量
def __init__(self,val):
print '__init__ is called!'
self.val=val
@staticmethod
def show():
print Singleton.__instance
def __new__(cls, *args, **kwd): # 在__init__之前调用
print '__new__ is called!'
if Singleton.__instance is None: # 生成唯一实例
Singleton.__instance = object.__new__(cls, *args, **kwd)
return Singleton.__instance
Singleton.show()
s1=Singleton(100)
print s1 #注意实例s1的内存地址
Singleton.show()
print s1.val
s2=Singleton(200)
print s2 #注意s2的内存地址与s1一样,因此是同一个实例,只是实例变量val的值发生了改变
Singleton.show()
print s2.val
运行结果:
None
__new__ is called!
__init__ is called!
<__main__.Singleton object at 0x029EF910>
<__main__.Singleton object at 0x029EF910>
100
__new__ is called!
__init__ is called!
<__main__.Singleton object at 0x029EF910>
<__main__.Singleton object at 0x029EF910>
200
__getattr__()、__setattr__()和__getattribute__():
当读取对象的某个属性时,python会自动调用__getattr__()方法.例如,fruit.color将转换为fruit.__getattr__(color).
当使用赋值语句对属性进行设置时,python会自动调用__setattr__()方法.
__getattribute__()的功能与__getattr__()类似,用于获取属性的值.但是__getattribute__()能提供更好的控制,代码更健壮.
注意,python中并不存在__setattribute__()方法.
代码例子:
class Fruit(object):
def __init__(self, color = "red", price = 0):
self.__color = color
self.__price = price
def __getattribute__(self, name): # 获取属性的方法
return object.__getattribute__(self, name)
def __setattr__(self, name, value):
self.__dict__[name] = value
if __name__ == "__main__":
fruit = Fruit("blue", 10)
print fruit.__dict__
#print fruit.__price #实例的私有属性,外界不可直接访问
print fruit.__dict__.get("_Fruit__color") # 获取color属性
fruit.__dict__["_Fruit__price"] = 5 # 修改price属性
print fruit.__dict__.get("_Fruit__price") # 获取price属性
__getitem__():
如果类把某个属性定义为序列,可以使用__getitem__()输出序列属性中的某个元素,假设水果店中销售多钟水果,可以通过__getitem__()方法获取水果店中的某种水果。
代码例子:
class FruitShop(object):
def __init__(self):
self.fruits = ["apple", "banana"]
def __getitem__(self, i):
#print '_getitem__ is called!'
# 获取水果店的水果
return self.fruits[i]
if __name__ == "__main__":
shop = FruitShop()
print shop.fruits #访问fruits变量
print shop.fruits[1]
print '----------'
print shop[1] #实际上,调用了__getitem__方法
for item in shop: # 输出水果店的水果(多次调用__getitem__方法)
print item,
print '\n---------'
for item in shop.fruits: # 输出水果店的水果(遍历列表,没有调用__getitem__方法)
print item,
运行结果:
['apple', 'banana']
banana
----------
banana
apple banana
---------
apple banana
__str__():
__str__()用于表示对象代表的含义,返回一个字符串.实现了__str__()方法后,可以直接使用print语句输出对象,
也可以通过函数str()触发__str__()的执行.这样就把对象和字符串关联起来,便于某些程序的实现,可以用这个字符串来表示某个类。
代码例子:
class Fruit:
'''this is the class of Fruit!''' #为Fruit类定义了文档字符串
def __str__(self): # 定义对象的字符串表示
print '__str__ is called!'
return self.__doc__
if __name__ == "__main__":
fruit = Fruit()
print fruit.__doc__,Fruit.__doc__
print str(fruit) #调用内置函数str(),触发了__str__()方法
print fruit #直接输出实例fruit,实际上是调用了__str__()方法
运行结果:
this is the class of Fruit! this is the class of Fruit!
__str__ is called!
this is the class of Fruit!
__str__ is called!
this is the class of Fruit!
__call__():
若在类中实现了__call__()方法,则该类的实例也是可调用的,调用该实例时,实际上是调用了__call__方法。使用该方法可以模拟静态方法。
代码例子:
class Fruit:
class Growth: # 定义内部类(属于外部类Fruit的类属性,可以通过类名Fruit直接访问)
def __call__(self):#类一定是可调用的,若该类内定义了__call__方法,则该类的实例也是可调用的。
print '__call__ is called!'
print "grow ..."
grow = Growth() #生成一个实例grow,grow属于Fruit的 类变量,可以通过类名Fruit直接访问
'''由于Growth类内定义了__call__方法,因此实例grow也是可调用的。
实际上是为外部类Fruit定义方法grow(),grow()将执行__call__()内的代码 '''
def __init__(self,name):
print 'Fruit.__init__ is called!'
self.name=name #定义实例变量
if __name__ == '__main__':
fruit = Fruit('apple')#自动调用构造函数__init__
print fruit.name #访问实例变量name
print '----------'
fruit.grow()
'''实例fruit并没有grow属性,访问的是类Fruit的grow属性,
调用该属性,实际上是调用了相应的__call__方法'''
Fruit.grow() #调用Fruit类的grow属性(实例grow是可调用的),实际上是调用了__call__方法
print '----------'
g=Fruit.Growth()#Growth是Fruit类的 类变量,可以通过类名直接访问
g()#定义了__call__方法的类的 实例 也是可调用的,调用该实例实际上是调用了__call__方法
运行结果:
Fruit.__init__ is called!
apple
----------
__call__ is called!
grow ...
__call__ is called!
grow ...
----------
__call__ is called!
grow ...
原文地址:点击打开链接