Python 高级面向对象

一、字段

  1、字段包括:普通字段和静态字段,他们在定义和使用中有所区别,而最本质的区别是内存中保存的位置不同。

    a、普通字段属于对象(实例变量)

    b、静态字段属于类(类变量)

      

二、属性

  对于属性,有以下三个知识点:

    属性的基本使用

    属性的两种定义方式

  1、属性的基本使用

    a、类是不能访问实例变量的

    
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 # 作者:Presley
 4 # 邮箱:1209989516@qq.com
 5 # 时间:2018-08-05
 6 # 类的方法
 7 class Animal:
 8     def __init__(self,name):
 9         self.name = name
10         self.num = None
11     count = 10
12     hobbie = "wohaoshuai"
13 
14     @classmethod #将下面方法变成只能通过类方式去调用而不能通过实例方式去调用。因此调用方法为:Animal.talk(). !!!!类方法,不能调用实例变量
15     def talk(self):
16         print("{0} is talking...".format(self.hobbie))#因为hobbie为类变量所以可以通过类方式或者实例方式,若括号中为self.name实例变量则只能通过Animal.talk()方式调用
17 
18     @staticmethod #当加上静态方法后,此方法中就无法访问实例变量和类变量了,相当于把类当作工具箱,和类没有太大关系
19     def walk():
20         print("%s is walking...")
21 
22     @property #属性,当加了property后habit就变成一个属性了就不再是一个方法了,调用时不用再加()
23     def habit(self): #习惯
24         print("%s habit is xxoo" %(self.name))
25 
26     @property
27     def total_players(self):
28         return  self.num
29 
30     @total_players.setter
31     def total_players(self,num):
32         self.num = num
33         print("total players:",self.num)
34 
35     @total_players.deleter
36     def total_players(self):
37         print("total player got deleted.")
38         del self.num
39 #@classmethod
40 # Animal.hobbie
41 # Animal.talk()
42 # d = Animal("wohaoshuai")
43 # d.talk()
44 
45 
46 # @staticmethod
47 # d = Animal("wohaoshuai2")
48 # d.walk()
49 
50 # @property
51 d = Animal("wohaoshuai3")
52 # d.habit
53 
54 #@total_players.setter
55 
56 print(d.total_players)
57 d.total_players = 2
58 
59 #@total_players.deleter
60 
61 del d.total_players
62 print(d.total_players)(报错,提示num不存在,因为已经被删除了)
原文地址:https://www.cnblogs.com/Presley-lpc/p/9824690.html