1.__str__
class Student(object): def __init__(self, name): self._name = name m = Student("michael") print m
<__main__.Student object at 0x0000000003280EF0>
为了使print类的结果格式更加方便阅读
重写__str__(self)
class Student(object): def __init__(self, name): self._name = name def __str__(self): return "Student Name is %s !"% self._name m = Student("michael") print m
Student Name is michael !
__repr__类似与__str__,不同的__repr__主要运用与开发者交互方面
2.__iter__
将类变为可迭代的类型
class Fib(object): def __init__(self): self.a = 0 self.b = 1 def __iter__(self): return self def next(self): self.a, self.b = self.b, self.a + self.b if self.a > 100: raise StopIteration() return self.a for n in Fib(): print n
3.__getitem__
用于迭代的时候,能用数组下标访问其中的变量
class Fib(object): def __init__(self): self.a = 0 self.b = 1 def __iter__(self): return self def next(self): self.a, self.b = self.b, self.a + self.b if self.a > 100: raise StopIteration() return self.a def __getitem__(self, item): for i in range(item): self.a, self.b = self.b, self.a + self.b return self.a print Fib()[11]
4.__getattr__
直接上例子:
class Person(object): def __init__(self): self.name = "Michael" def __getattr__(self, item): if item == "age": self.age = 22 return self.age m = Person() print m.__getattr__("age")
附上一个动态生成路径的代码
class Clain(object): def __init__(self, path=""): self._path = path def __getattr__(self, item): return Clain("%s/%s"%(self._path, item)) def __str__(self): return self._path print Clain().usr.bin.env.python
/usr/bin/env/python
5.__call__
直接调用实例
上个例子:
class Person(object): def __init__(self): self.name = "Michael" def __call__(self, *args, **kwargs): print "My name is %s" % self.name m = Person() m()
My name is Michael
附:__getattr__ 和 __call__ 联合调用
class Clain(object): def __init__(self, path=""): self._path = path def __getattr__(self, item): return Clain("%s/%s"%(self._path, item)) def __str__(self): return self._path def __call__(self, *args, **kwargs): for i in args: self._path = "%s/%s" % (self._path, i) return Clain(self._path) print Clain().usr("Michael").bin.env.python
/usr/Michael/bin/env/python
时间: 2024-10-20 20:04:05