python中的實例方法、靜態方法、類方法、類變量和實例變量


class MyTest:

    myname = 'peter'

    # add a instance attribute
    def __init__(self, name):
        self.name = name

    # class access class attribute
    def sayhello(self):
        print "say hello to %s" % MyTest.myname

    # instance can access class attribute
    def sayhello_1(self):
        print "say hello to %s" % self.myname

    # It's a snap! instance can access instance attribute
    def sayhello_2(self):
        print "say hello to %s" % self.name

    # class can not access instance attribute!!!
    def sayhello_3(self):
        #print "say hello to %s" % MyTest.name
        pass

if __name__ == '__main__':

    test = MyTest("abc")
    test.sayhello()
    test.sayhello_1()
    test.sayhello_2()
    test.sayhello_3()

    # class's definition can be changed dynamically
    MyTest.yourname = "Allen"

    print MyTest.myname
    print MyTest.yourname

 ---------------------------------------------------------------------------------------------------------------------

class Foo:

    def func(self):
        print "object method"

    @classmethod
    def cfunc(cls):
        print "class method"

    @staticmethod
    def sfunc(a, b):
        print "static method:", a, " + ", b, "=", a + b


if __name__ == '__main__':
    foo = Foo()
  

    # instance method can be called by object and class name
    foo.func()
    Foo.func(foo)

     # both instance and class can call class method
    foo.cfunc()
    Foo.cfunc()

     # both instance and class can call static method
    Foo.sfunc(10, 20)
    foo.sfunc(50, 100)

 ----------------------------------------------------------------------------------------------------------------------

注:使用的是Python2.7。

一、實例方法

實例方法就是類的實例能夠使用的方法。如下:

class Foo:
    def __init__(self, name):
        self.name = name
    def hi(self):
        print self.name

if __name__ == '__main__':
    foo01 = Foo('letian')
    foo01.hi()
    print type(Foo)
    print type(foo01)
    print id(foo01)
    print id(Foo)

運行結果為:
letian
<type 'classobj'>
<type 'instance'>
40124704
31323448[code]
可以看到,Foo的type為classobj(類對象,python中定義的類本身也是對象),foo01的type為instance(實例)。而hi()是實例方法,所以foo01.hi()會輸出'letian'。實例方法的第一個參數默認為self,代指實例。self不是一個關鍵字,而是約定的寫法。init()是生成實例時默認調用的實例方法。將Foo的定義改為以下形式:
class Foo:
    def __init__(this, name):
        this.name = name
    def hi(here):
        print here.name

運行依然正確。 內置函數id用來查看對象的標識符,下面是其doc內容:

>>> print id.__doc__
id(object) -> integer

Return the identity of an object.  This is guaranteed to be unique among
simultaneously existing objects.  (Hint: it's the object's memory address.)

二、靜態方法

靜態方法是一種普通函數,就位於類定義的命名空間中,它不會對任何實例類型進行操作。使用裝飾器@staticmethod定義靜態方法。類對象和實例都可以調用靜態方法

class Foo:
    def __init__(self, name):
        self.name = name
    def hi(self):
        print self.name
    @staticmethod
    def add(a, b):
        print a + b

if __name__ == '__main__':
    foo01 = Foo('letian')
    foo01.hi()
    foo01.add(1,2)
    Foo.add(1, 2)

運行結果如下:
letian
3
3

三、類方法

類方法是將類本身作為對象進行操作的方法。類方法使用@classmethod裝飾器定義,其第一個參數是類,約定寫為cls。類對象和實例都可以調用類方法

class Foo:
    name = 'letian '
    @classmethod
    def hi(cls, x):
        print cls.name * x

if __name__ == '__main__':
    foo01 = Foo()
    foo01.hi(2)
    Foo.hi(3)


運行結果如下:

letian letian
letian letian letian


注意,很多其他的編程語言不允許實例調用類方法。

四、super

super用來執行父類中的函數,例如:

class Foo(object):
    def hi(self):
        print 'hi,Foo'

class Foo2(Foo):
    def hi(self):
        super(Foo2, self).hi()

if __name__ == '__main__':
    foo2 = Foo2()
    foo2.hi()


運行結果:

hi,Foo


注意,Foo類必須繼承某個類(並且這個繼承鏈開始於object類),否則會報錯。如果改成下面的形式:

class Foo:
    def hi(self):
        print 'hi,Foo'

class Foo2(Foo):
    def hi(self):
        super(Foo2, self).hi()

if __name__ == '__main__':
    foo2 = Foo2()
    foo2.hi()


運行時報錯如下:

......
TypeError: must be type, not classobj


關於super,具體請見http://docs.python.org/2/library/functions.html?highlight=super#super以及super.doc。


五、類變量和實例變量

類變量定義在類的定義之后,實例變量則是以為self.開頭。例如:

class Foo(object):
    val = 0
    def __init__(self):
        self.val = 1

if __name__ == '__main__':
    foo = Foo()
    print foo.val
    print Foo.val


運行結果為:

1
0


實例也能夠訪問類變量,如下:

class Foo(object):
    val = 0
    def __init__(self):
        pass
if __name__ == '__main__':
    foo = Foo()
    print foo.val
    print Foo.val


運行結果如下:

0
0


另外,可以通過以下方式訪問類變量:

class Foo(object):
    val = 3
    def __init__(self):
        print self.__class__.val
if __name__ == '__main__':
    foo = Foo()

運行結果:

3


還可以這樣:

class Foo(object):
    val = 3
    def __init__(self):
        pass
    @classmethod
    def echo(cls):
        print cls.val
if __name__ == '__main__':
    Foo.echo()

運行結果:

3

六、如何調用父類的構造函數

子類(派生類)並不會自動調用父類(基類)的init方法,例如:

class Foo(object):
    def __init__(self):
        self.val = 1

class Foo2(Foo):
    def __init__(self):
        print self.val

if __name__ == '__main__':
    foo2 = Foo2()


運行時報錯。

調用父類的init方法有兩種,第一種:

class Foo(object):
    def __init__(self):
        self.val = 1

class Foo2(Foo):
    def __init__(self):
        Foo.__init__(self)   //類調用實例方法時,需要傳入self指代的實例
        print self.val

if __name__ == '__main__':
    foo2 = Foo2()


第二種:

class Foo(object):
    def __init__(self):
        self.val = 1

class Foo2(Foo):
    def __init__(self):
        super(Foo2, self).__init__() 
        print self.val

if __name__ == '__main__':
    foo2 = Foo2()


這兩種方法的運行結果均為:

1


不過這兩種方法是有區別的。


免責聲明!

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



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