码迷,mamicode.com
首页 > 其他好文 > 详细

定制类

时间:2016-06-17 23:48:40      阅读:379      评论:0      收藏:0      [点我收藏+]

标签:

class Student(object):
    pass
s = Student()
s.name = Michael
print(s.name)

def set_age(self, age):
    self.age = age
from types import MethodType
s.set_age = MethodType(set_age, s) #给实例绑定一个方法
s.set_age(25)
print(s.age)
#注意给一个实例绑定的方法对于另一个实例是不起作用的
s2 = Student() #创建新的实例
#为了给所有的实例都绑定方法,可以给class绑定方法
def set_score(self, score):
    self.score = score
Student.set_score = set_score
s.set_score(100)
print(s.score)
s2.set_score(99)
print(s2.score)

#如果我们想限制类的属性,比如,只允许对Student实例添加name和age属性
#__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的:
#除非在子类中也定义__slots__,这样,子类实例允许定义的属性就是自身的__slots__加上父类的__slots__。
class Student(object):
    __slots__ = (name, age)
s = Student()
s.name = Michael
s.age = 25
#s.score = 99 #因为__slots__(‘name‘, ‘age‘)限制Student实例只能添加name和age属性

class Teacher(object):
    def __init__(self, name, subject):
        self.name = name
        self.subject = subject
t = Teacher(wangxin, math)
print(t.name)
print(t.subject)

class Student(object):
    def __init__(self, name):
        self.name = name
print(Student(Michael))

class Student(object):
    def __init__(self, name):
        self.name = name
    def __str__(self):
        return Student object (name:%s) %self.name
    __repr__ = __str__
print(Student(Michael))

class Fib(object):
    def __init__(self):
        self.a, self.b = 0, 1
    def __iter__(self):
        return self
    def __next__(self):
        self.a, self.b = self.b, self.a+self.b
        if self.a > 100000:
            raise StopIteration();
        return self.a
for n in Fib():
    print(n)
#要表现得像list那样按照下标取出元素,需要实现__getitem__()方法:
class Fib(object):
    def __getitem__(self, n):
        a, b = 1, 1
        for x in range(n):
            a, b = b, a+b
        return a
f = Fib()
print(f[0])
print(list(range(100))[5:10])

class Fib(object):
    def __getitem__(self, n):
        if isinstance(n, int):
            a, b = b, a+b
        return a
        if isinstance(n, slice):
            start = n.start
            stop =  n.stop
            if start is None:
                start = 0
            a, b = 1, 1
            L = []
            for x in range(stop):
                if x >= start:
                    L.append(a)
                a, b = b, a+b
            return L
f = Fib()
print(---------)
print(f[0:5])

 

定制类

标签:

原文地址:http://www.cnblogs.com/rain-1/p/5595285.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!