1. 程式人生 > >python基礎-----面向物件程式設計

python基礎-----面向物件程式設計

class Animal(object):
    mao = 'mao'   #靜態欄位   --》》屬於類
    
    #在__init__ 方法中的屬於動態欄位  --->>屬於物件  相當於建構函式
    def __init__(self, name, age, sex, feet):
        self.name = name
        self.age = age
        
        #定義一個私有欄位
        self.__sex = sex
        
        self.__feet = feet
        
    #動態方法
    def sport_meet(self):
        print self.name + 'run....'
        
    def FwSex(self):
        print "訪問私有欄位"+self.__sex
        
    #靜態方法
    @staticmethod
    def Foo():
        print 'fly...'
     
    #把方法訪問的形式變成欄位訪問的形式
    @property
    def voice(self):
        print self.name+"voice..."
        
        return 'voice' #用property一般都帶返回值
    
    #定義一個私有方法
    def __PrivateMethod(self):
        print 'privateMethod....'
    
    #本身共有方法,可以訪問私有方法
    def PublicMethod(self):
        self.__PrivateMethod()
    
    @property #只讀
    def Feet(self):
        return self.__feet
    
    @Feet.setter  #只寫
    def Feet(self, feet):
        self.__feet = feet
    
animal = Animal('天氣', 34, '__sex','1111')
# print animal.name
# print Animal.Foo()
# print animal.voice
# 
# # print animal.__sex #訪問報錯(Animal instance has no attribute '__sex')
# print animal.FwSex()
# 
# animal.__PrivateMethod()  #訪問不了私有方法報錯(Animal instance has no attribute '__PrivateMethod')
print animal.Feet
animal.Feet = '12222'
print animal.Feet