Class

作者: Modelstrategy | 来源:发表于2017-12-24 17:19 被阅读0次
    # 请把下面的Student对象的gender字段对外隐藏起来,用get_gender()和set_gender()代替,并检查参数有效性:
    
    class Student(object):
        def __init__(self, name, gender):
            self.name = name
            self.__gender = gender
    
        def set_gender(self, gender):
            self.__gender = gender
            print(gender)
    
        def get_gender(self):
            return self.__gender
    
    ein_sehr_sehr_böser_student = Student('Alex','male')
    
    print(ein_sehr_sehr_böser_student.get_gender())
    print(ein_sehr_sehr_böser_student._Student__gender)  # 这是在做坏事
    
    
    # 继承
    class Studentin(Student):
    
        def set_gender(self, gender):
            if gender == 'male':
                print('you sure???')
    
            else:
                self.__gender = gender
    
    Hahna = Studentin('Ahrent', 'female')
    print('Hahna: ', Hahna.get_gender())
    Hahna.set_gender('male')
    
    def list_student(student):
        print('name: ', student.name)
        print('genger: ', student.get_gender())
    
    
    # dir(), hasattr(), setattr(), getattr()  ( 竟然用了第三人称单数,也是够了)
    
    
    class MyObject(object):
        def __init__(self, x = 9):
            self.x = x
    
            def power(self):
                return self.x * self.x
    
    this_is_an_object = MyObject()
    print(hasattr(this_is_an_object,'x'))
    setattr(this_is_an_object, 'x', 19)
    print(getattr(this_is_an_object, 'x'))
    
    print(hasattr(this_is_an_object, 'y'))
    setattr(this_is_an_object, 'y', 20)
    print(hasattr(this_is_an_object, 'y'))
    print(getattr(this_is_an_object, 'y'))
    
    
    # 实例属性和类属性
    # 为了统计学生人数,可以给Student类增加一个类属性,每创建一个实例,该属性自动增加:
    
    
    class Studentinen():
        __count = 0
    
        def __init__(self, name):
    
            self.name = name
            Studentinen.__count += 1   # not self.__count !!!
            print('total number: ', Studentinen.__count)
    
        @classmethod
        def studenten_nummer(cls):
            print('the number of students is: ', cls.__count)   # cls(class) / cls.__count equals Studentinen.__count
    
    
    Lisa = Studentinen("Lisa")
    Siri = Studentinen('Siri')
    Sami = Studentinen('Sami')
    Sami.studenten_nummer()
    
    # 给实例绑定方法
    
    
    def set_score(self, score):
        self.__score = score
        print('score has been set to: ', self.__score)
    
    
    from types import MethodType
    
    Lisa.set_score = MethodType(set_score, Lisa)
    Lisa.set_score(98)
    # Siri.set_score(100)     # 针对于实例所绑定的方法,只对该实例有效,无法应用于所有实例
    
    # 为了给所有实例都绑定方法,可以给class绑定方法
    
    Studentinen.set_score = set_score    # 不需要使用methodtype
    Siri.set_score(100)
    
    # 使用__slots__限制实例的属性
    
    class Student(object):
        def __init__(self, name, gender, score = 0):
            self.name = name
            self.__gender = gender
            self.score = score
    
        __slots__ = ('name', '__gender')   # 使用slots 限制
    
        def set_gender(self, gender):
            self.__gender = gender
            print(gender)
    
        def get_gender(self):
            return self.__gender
    
    Alex = Student('Alex', 'male')
    print(Alex.get_gender())
    Alex.score = 100
    print(Alex.score)
    
    
    class Studentin(Student):
    
        def set_gender(self, gender):
            if gender == 'male':
                print('you sure???')
    
            else:
                self.__gender = gender
    
    hahna = Studentin('Hahna','female')
    hahna.score = 100           #  __slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用的
    print(hahna.score)
    
    
    class Studentin(Student):
        __slots__ = ('name', 'gender')
        def set_gender(self, gender):
            if gender == 'male':
                print('you sure???')
    
            else:
                self.__gender = gender
    
    
    Alexis = Studentin('Alexis', 'female')      #  子类实例允许定义的属性就是自身的__slots__加上父类的__slots__
    Alexis.score = 100
    
    # 请利用@property给一个Screen对象加上width和height属性,以及一个只读属性resolution
    
    class Screen(object):
    
        @property
        def width(self):      # you can't change the name of the method
            return self._width
    
        @width.setter
        def width(self, width):   # you can't change the name of the method
            self.__width = width
    
        @property
        def height(self):
            return self.__height
    
        @height.setter
        def height(self, height):
            self.__height = height
    
        @property
        def resolution(self):
            return self.__height * self.__width
    
    s = Screen()
    s.width = 1024
    s.height = 768
    print(s.resolution)
    
    # 定制类
    # __str__
    
    
    class Teacher(object):
        def __init__(self, name):
            self.name = name
    
    
    print(Teacher('Alex'))
    # <__main__.Teacher object at 0x10c97d3c8>
    
    
    class Teacher(object):
        def __init__(self, name):
            self.name = name
    
        def __str__(self):
            return 'Teacher Object, (name: %s)' % self.name
    
    
    print(Teacher('Alex'))
    # Teacher Object, (name: Alex)
    
    class Teacher(object):
        def __init__(self, name):
            self.name = name
    
        def __str__(self):
            return 'Teacher Object, (name: %s)' % self.name
    
        __repr__ = __str__
    
    
    # __iter__
    
    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  > 100:
                raise StopIteration
            return self.a
    
    for i in Fib():
        print(i)
    
    # __getitem__()
    
    
    class Fib2(object):
    
        def __init__(self):
            self.a, self.b = 0, 1
    
        def __getitem__(self, n):
            self.a, self.b = 1, 1
            for i in range(n):
                self.a, self.b = self.b, self.a + self.b
    
            return self.a
    
    
    print(Fib2()[5])
    
    # 添加切片功能
    class Fib3(object):
    
        def __getitem__(self, n):
            a, b = 1, 1
            if isinstance(n, int):
                for i in range(n):
                    a, b = b, a + b
                return a
    
            elif isinstance(n, slice):
                start = n.start
                stop = n.stop
    
                if start is None:
                    start = 0
    
                L = []
    
                for i in range(stop):
                    if i >= start:
                        L.append(a)
                        a, b = b, a + b
    
                return L
    
    
    print('calling single selected element: %d' % Fib3()[6])
    print('calling slice: %s' % Fib3()[0:6])
    
    
    

    相关文章

      网友评论

          本文标题:Class

          本文链接:https://www.haomeiwen.com/subject/aquhgxtx.html