1. 程式人生 > >python~動態語言

python~動態語言

python是動態語言

動態語言的定義

動態程式語言 是 高階程式設計語言 的一個類別,在電腦科學領域已被廣泛應用。它是一類 在執行時可以改變其結構的語言 :例如新的函式、物件、甚至程式碼可以被引進,已有的函式可以被刪除或是其他結構上的變化。動態語言目前非常具有活力。例如JavaScript便是一個動態語言,除此之外如 PHP 、 Ruby 、 Python 等也都屬於動態語言,而 C 、 C++ 等語言則不屬於動態語言。----來自 維基百科

執行的過程中給物件繫結(新增)屬性

>>> class Person(object):
    def __init__(self, name = None, age = None):
        self.name = name
        self.age = age


>>> P = Person("小明", "24")
>>>

在這裡,我們定義了1個類Person,在這個類裡,定義了兩個初始屬性name和age,但是人還有性別啊!如果這個類不是你寫的是不是你會嘗試訪問性別這個屬性呢?

>>> P.sex = "male"
>>> P.sex
'male'
>>>

這時候就發現問題了,我們定義的類裡面沒有sex這個屬性啊!怎麼回事呢? 這就是動態語言的魅力和坑! 這裡 實際上就是 動態給例項繫結屬性!

 執行的過程中給類繫結(新增)屬性

>>> P1 = Person("小麗", "25")
>>> P1.sex

Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    P1.sex
AttributeError: Person instance has no attribute 'sex'
>>>

我們嘗試列印P1.sex,發現報錯,P1沒有sex這個屬性!---- 給P這個例項繫結屬性對P1這個例項不起作用! 那我們要給所有的Person的例項加上 sex屬性怎麼辦呢? 答案就是直接給Person繫結屬性!

>>>> Person.sex = None #給類Person新增一個屬性
>>> P1 = Person("小麗", "25")
>>> print(P1.sex) #如果P1這個例項物件中沒有sex屬性的話,那麼就會訪問它的類屬性
None #可以看到沒有出現異常
>>>

執行的過程中給類繫結(新增)方法

我們直接給Person繫結sex這個屬性,重新例項化P1後,P1就有sex這個屬性了! 那麼function呢?怎麼繫結?

>>> class Person(object):
    def __init__(self, name = None, age = None):
        self.name = name
        self.age = age
    def eat(self):
        print("eat food")


>>> def run(self, speed):
    print("%s在移動, 速度是 %d km/h"%(self.name, speed))


>>> P = Person("老王", 24)
>>> P.eat()
eat food
>>> 
>>> P.run()
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    P.run()
AttributeError: Person instance has no attribute 'run'
>>>
>>>
>>> import types
>>> P.run = types.MethodType(run, P)
>>> P.run(180)
老王在移動,速度是 180 km/h

既然給類新增方法,是使用類名.方法名 = xxxx,那麼給物件新增一個方法也是類似的物件.方法名 = xxxx

完整的程式碼如下:



import types

#定義了一個類
class Person(object):
    num = 0
    def __init__(self, name = None, age = None):
        self.name = name
        self.age = age
    def eat(self):
        print("eat food")

#定義一個例項方法
def run(self, speed):
    print("%s在移動, 速度是 %d km/h"%(self.name, speed))

#定義一個類方法
@classmethod
def testClass(cls):
    cls.num = 100

#定義一個靜態方法
@staticmethod
def testStatic():
    print("---static method----")

#建立一個例項物件
P = Person("老王", 24)
#呼叫在class中的方法
P.eat()

#給這個物件新增例項方法
P.run = types.MethodType(run, P)
#呼叫例項方法
P.run(180)

#給Person類繫結類方法
Person.testClass = testClass
#呼叫類方法
print(Person.num)
Person.testClass()
print(Person.num)

#給Person類繫結靜態方法
Person.testStatic = testStatic
#呼叫靜態方法
Person.testStatic()

執行的過程中刪除屬性、方法

刪除的方法:

  1. del 物件.屬性名
  2. delattr(物件, "屬性名")

通過以上例子可以得出一個結論:相對於動態語言,靜態語言具有嚴謹性!所以,玩動態語言的時候,小心動態的坑!

那麼怎麼避免這種情況呢? 請使用__slots__,