Python3类之四

#类与对象#
#!r 就是 repr
#!s 就是 str
#!a 就是 ascii
class Pair :
    def __init__(self,x,y) :
        self.x = x
        self.y = y
    def __repr__(self) : 
        return 'Pair({0.x!r}, {0.y!r})'.format(self)
    def __str__(self) :
        return '({0.x!s}, {0.y!s})'.format(self)
p = Pair(3,4)
print ('p is {0!r}'.format(p))###p is Pair(3, 4)
print ('p is {0}'.format(p))##p is (3, 4)
#当创建了大量的实例时如何节省内存
#对于那些主要用作简单数据结构的类,通常可以在类的定义中增加'__slots__属性' ,以此来大量减少对内存的使用
#限制使用了__slots__中列出的那些属性名
class  Date :
    __slots__ = ['year','month','day']
    def __init__(self,year,month,day) :
        self.year = year
        self.month = month
        self.day = day
########################
#将名称封装到类中

class B:
    def __init__(self) :
        self.__private = 0
    def __private_method(self) :
        print ("I,m a private function and outside cant't see me directly !!")
test = B()######################
print ("test._B__private:",test._B__private)################Note:::
test._B__private_method()#######

#这种命名不能通过继承而被覆盖
class C(B):
    def __init__(self) :
        super().__init__() 
        self.__private = 1##Does not override by B.__private 
    def __private_method(self):###the same as above
        print ("I'm a private function and not inheritance B")
testc = C()
print ("testc._C__private:",testc._C__private)
testc._C__private_method()
###
class Person:
    def __init__(self, first_name):
        self.first_name = first_name

    # Getter function
    @property
    def first_name(self):
        return self._first_name

    # Setter function
    @first_name.setter
    def first_name(self, value):
        if not isinstance(value, str):
            raise TypeError('Expected a string')
        self._first_name = value

if __name__ == '__main__':
   a = Person('Guido')
   print(a.first_name)
   a.first_name = 'Dave'
   print(a.first_name)
   try:
       a.first_name = 42
   except TypeError as e:
       print(e)

 

posted @ 2018-09-21 14:19  凤舞琦天  阅读(89)  评论(0)    收藏  举报
https://files.cnblogs.com/files/liuguoqi/weinxin.bmp