面向對象python
面向對象編程——Object Oriented Programming,簡稱OOP,是一種程序設計思想。OOP把對象做爲程序的基本單元,一個對象包含了數據和操做數據的函數編程
class car: #靜態字段,類屬性 cars='車的種類之一' def __init__(self,name): #動態字段,實例屬性 self.name=name car1=car('寶馬') print(car1.name) print(car.cars) print(car1.cars)
定義1個對象:class xxx:函數
實例化1個對象:def __init__(self,value) spa
__init__ 是初始化的意思.net
定義car(車)這個類,而寶馬這個實例對象擁有 name屬性設計
經過字典,一次性取出實例對象全部屬性 __dict__code
class People: def __init__(self,name,sex,number,age): self.name=name self.sex=sex self.number=number self.age=age p1=People('SBharmel','man',1350023,16) print(p1.__dict__) #經過字典,一次性取出,對象全部屬性 #輸出結果: #{'name': 'SBharmel', 'number': 1350023, 'sex': 'man', 'age': 16}
從屬關係對象
cars 屬於 car 類 類不能訪問動態字段get
name 屬於 car1 對象 對象能夠訪問動態字段和靜態字段it
只有是從屬關係,才能用 .xxx 方法獲取
因此能夠寫 car.cars #獲取靜態字段 car1.name #獲取動態字段
若是寫成 car.name 則會報錯
不能寫的緣由:
1.從屬關係不一樣
2. 車這個類可能擁有多個類型如 寶馬, 奔馳 他們兩個的屬性不同,如價格,車速不一樣
#可是對象能夠獲取 靜態字段 car1.cars
由於 car1 也屬於 這個類 (car)
class car: def __init__(self,name,speed,price): self.name=name self.speed=speed self.price=price car1=car('寶馬','130km/h','100w') car2=car('奔馳','140km/h','80w') print(car1.name) #正確 print(car2.price) #正確 print(car.speed) #報錯 ''' Traceback (most recent call last): File "E:\workspace\day4\backend\class.py", line 23, in <module> print(car.speed) AttributeError: type object 'car' has no attribute 'speed' '''
靜態字段和動態字段
類建立的字段叫作 靜態字段 cars
.sefl 建立的字段叫作 動態字段 name
靜態方法(@staticmethod)和動態方法以及特性( property)
@staticmethod #構造的函數()裏面不傳參數self
def foo()
@property #構造的函數 ()裏面要傳參數 self,調用不用寫()
hb.bar #僅爲實例對象的特性,類調用無內容
class Province: def __init__(self,name): self.name=name #動態方法 def meeting(self): print(self.name+'正在開運動會') #靜態方法 @staticmethod def foo(): print('每一個省要堅持環保') #特性 @property def bar(self): print('someting') hb=Province('湖北') hb.meeting() Province.foo() hb.bar
。