1. 程式人生 > >Python 高級面向對象

Python 高級面向對象

none idt 變量 ota elf 不存在 類方法 animal prope

一、字段

  1、字段包括:普通字段和靜態字段,他們在定義和使用中有所區別,而最本質的區別是內存中保存的位置不同。

    a、普通字段屬於對象(實例變量)

    b、靜態字段屬於類(類變量)

      技術分享圖片

二、屬性

  對於屬性,有以下三個知識點:

    屬性的基本使用

    屬性的兩種定義方式

  1、屬性的基本使用

    a、類是不能訪問實例變量的

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 作者:Presley
# 郵箱:[email protected]
# 時間:2018-08-05
# 類的方法
class Animal:
def __init__(self,name):
self.name = name
self.num = None
count = 10
hobbie = "wohaoshuai"

@classmethod #將下面方法變成只能通過類方式去調用而不能通過實例方式去調用。因此調用方法為:Animal.talk(). !!!!類方法,不能調用實例變量
def talk(self):
print("{0} is talking...".format(self.hobbie))#因為hobbie為類變量所以可以通過類方式或者實例方式,若括號中為self.name實例變量則只能通過Animal.talk()方式調用

@staticmethod #當加上靜態方法後,此方法中就無法訪問實例變量和類變量了,相當於把類當作工具箱,和類沒有太大關系
def walk():
print("%s is walking...")

@property #屬性,當加了property後habit就變成一個屬性了就不再是一個方法了,調用時不用再加()
def habit(self): #習慣
print("%s habit is xxoo" %(self.name))

@property
def total_players(self):
return self.num

@total_players.setter
def total_players(self,num):
self.num = num
print("total players:",self.num)

@total_players.deleter
def total_players(self):
print("total player got deleted.")
del self.num
#@classmethod
# Animal.hobbie
# Animal.talk()
# d = Animal("wohaoshuai")
# d.talk()


# @staticmethod
# d = Animal("wohaoshuai2")
# d.walk()

# @property
d = Animal("wohaoshuai3")
# d.habit

#@total_players.setter

print(d.total_players)
d.total_players = 2

#@total_players.deleter

del d.total_players
print(d.total_players)(報錯,提示num不存在,因為已經被刪除了)


Python 高級面向對象