Python定制类

定制类



打印类信息


class Person(object):

    def __init__(self, name, gender):
        self.name = name
        self.gender = gender

class Student(Person):

    def __init__(self, name, gender, score):
        super(Student, self).__init__(name, gender)
        self.score = score

    def __str__(self):
        return '(Student: %s, %s, %s)' % (self.name, self.gender, self.score)
    __repr__ = __str__

s = Student('Bob', 'male', 88)
print s

定义了 __str__  和 __repr__方法,定制自己的类对象的打印信息




定义类的比较函数


class Student(object):

    def __init__(self, name, score):
        self.name = name
        self.score = score

    def __str__(self):
        return '(%s: %s)' % (self.name, self.score)

    __repr__ = __str__

    def __cmp__(self, s):
        if self.score > s.score:
            return -1
        elif self.score < s.score:
            return 1
        else:
            if self.name > s.name:
                return 1
            else:
                return -1

L = [Student('Tim', 99), Student('Bob', 88), Student('Alice', 99)]
print sorted(L)



定义len函数


class Fib(object):
    
    def __init__(self, num):
        self.num = num
        mylist = [0,1]
        for i in range(1,num-1):
            mylist.append(mylist[-1] + mylist[-2])
        self.mylist = mylist
    
    def __str__(self):
        return '%s' %(self.mylist)
    def __len__(self):
        return len(self.mylist)
        

f = Fib(10)
print f
print len(f)



@property


class Student(object):

    def __init__(self, name, score):
        self.name = name
        self.__score = score

    @property
    def score(self):
        return self.__score

    @score.setter
    def score(self, score):
        if score < 0 or score > 100:
            raise ValueError('invalid score')
        self.__score = score

    @property
    def grade(self):
        if self.score >= 80:
            return 'A'
        elif self.score < 60:
            return 'C'
        else:
            return 'B'

s = Student('Bob', 59)
print s.grade

s.score = 60
print s.grade

s.score = 99
print s.grade



限制类的属性


class Person(object):

    __slots__ = ('name', 'gender')

    def __init__(self, name, gender):
        self.name = name
        self.gender = gender

class Student(Person):

    __slots__ = ('name','gender','score')

    def __init__(self,name,gender,score):
        super(Student,self).__init__(name,gender)
        self.score = score

s = Student('Bob', 'male', 59)
s.name = 'Tim'
s.score = 99
print s.score


__call__函数


class Fib(object):
    def __call__(self,num):
        mylist = [0,1]
        for i in range(1,num-1):
            mylist.append(mylist[-1] + mylist[-2])
        return mylist

f = Fib()
print f(10)

一个类实例也可以成为一个可调用对象,需要实现__call__方法。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值