首页 > 代码库 > python property属性

python property属性


能够检查參数,一直没注意这个语言特性,忽略了非常多细节,感谢 vitrox

class Person( object ):
    
    def __init__( self, name ):
        if not isinstance( name, str ):
            raise TypeError( '...' )
        else:
            self.__name = name
            
    @property
    def name( self ):
        print 'get name.'
        return self.__name


    @name.setter
    def name( self, newname ):
        print 'set name.'
        if not isinstance( newname, str ):
            raise TypeError( '...' )
        else:
            self.__name = newname
            print 'set ok.'
        

p = Person( 'A' )
p.name = 'B'
print p.name


python property属性