Python定制类

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

 

转载于:https://www.cnblogs.com/Msh0923/p/8095464.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值