码迷,mamicode.com
首页 > 编程语言 > 详细

Python 高级面向对象

时间:2018-10-21 13:33:32      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:alt   sel   类方法   com   实例   play   分享图片   class   coding   

一、字段

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

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

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

      技术分享图片

二、属性

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

    属性的基本使用

    属性的两种定义方式

  1、属性的基本使用

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

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 作者:Presley
# 邮箱:1209989516@qq.com
# 时间: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 高级面向对象

标签:alt   sel   类方法   com   实例   play   分享图片   class   coding   

原文地址:https://www.cnblogs.com/Presley-lpc/p/9824690.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!