Python面向對象—類屬性和實例屬性


屬性:就是屬於一個對象的數據或函數元素

類有類方法、實例方法、靜態方法、類數據屬性(類變量)和實例數據屬性(實例變量)。

類屬性:包括類方法和類變量,可以通過類或實例來訪問,只能通過類來修改。

實例屬性:包括實例方法和實例變量

class MyClass(object):
    name = 'Anl'

    def __init__(self, age):
        self.age = age

    @classmethod
    def class_method(cls):
        print 'class_name:', cls.name  #類方法訪問類變量
        print "I'm class method"

    def example_method(self):
        self.age = 20
        print 'example_name:', self.__class__.name  # 實例方法訪問類變量
        print "I'm a method, and age is %d" % self.age

    @staticmethod
    def static_method():
        print "I'm static method"

使用類來訪問類變量

MyClass.name   
#結果為 'Anl'

使用類來修改類變量

MyClass.name = 'Delav'  
print MyClass.name   
#結果為'Delav'

使用類來訪問類方法

MyClass.class_method()   
#結果為
class_name: Delav
I'm class method

使用類來訪問靜態方法

MyClass.static_method()   
#結果為
I'm static method

修改實例變量

ob = MyClass(20) #實例化
print ob.age     #結果為20
ob.age = 23      #修改實例屬性
print ob.age     #結果為23

使用實例來訪問類變量

print ob.name   #結果為 'Delav'

使用實例來訪問實例方法

ob.example_method(25)    
#結果為
example_name: Delav
I'm example method , and age is 25

使用實例來訪問類方法

ob.class_method()    
#結果為
class_name: Delav
I'm class method

使用實例來訪問靜態方法

ob.static_method()   #結果為 I'm static method

修改實例屬性,類變量不變,實例變量改變

ob.name = 'Bon'    
print MyClass.name  #結果為 Delav
print ob.name       #結果為 Bon

總的結果

 

a = MyClass(20)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM