Python面向对象之静态属性、类方法与静态方法分析

yipeiwu_com6年前Python基础

本文实例讲述了Python面向对象之静态属性、类方法与静态方法。分享给大家供大家参考,具体如下:

1. 静态属性:在函数前加@property,将函数逻辑”封装“成数据属性,外部直接调用函数名,如同调用属性一样。这个函数是可以调用对象和类的属性的。

# -*- coding:utf-8 -*-
class Room:
  def __init__(self,name,owner,width,length):
    self.name = name
    self.owner = owner
    self.width = width
    self.length = length
  @property
  def cal_area(self):
    return self.length * self.width
r1 = Room('卧室','alex',100,1000)
print(r1.cal_area)
#r1.cal_area = 10  并不是真实的数据属性,所以不可以在外部直接赋值。

运行结果:

100000

2. 类方法:在类的方法前添加@classmethod,不需要实例化,直接调用类的该方法。可以访问类的数据属性,但是不可以访问对象的数据属性。

# -*- coding:utf-8 -*-
class Room:
  style = '别墅'
  def __init__(self,name,owner,width,length):
    self.name = name
    self.owner = owner
    self.width = width
    self.length = length
  @property
  def cal_area(self):
    return self.length * self.width
  @classmethod
  def tell_style(cls):
    #这么写会报错,因为name是对象的数据属性,而类方法是不可以访问实例的属性的
    #print('%s的房间风格是%s'%(cls.name,cls.style))
    print('房间的风格是%s'%(cls.style))
#类方法的定义只是为了类去调用
Room.tell_style()

运行结果:

房间的风格是别墅

3. 静态方法:在类的方法前加@staticmethod,该方法只是名义上的归属类管理,实例和类的属性均不可以访问,仅仅是类的工具包。

# -*- coding:utf-8 -*-
class Room:
  style = '别墅'
  def __init__(self,name,owner,width,length):
    self.name = name
    self.owner = owner
    self.width = width
    self.length = length
  @property
  def cal_area(self):
    return self.length * self.width
  @classmethod
  def tell_style(cls):
    #这么写会报错,因为name是对象的数据属性,而类方法是不可以访问实例的属性的
    #print('%s的房间风格是%s'%(cls.name,cls.style))
    print('房间的风格是%s'%(cls.style))
  @staticmethod
  def shower():
    print("洗澡")
  def test(self):
    print("这不是静态方法,而且自动生成参数,必须要有实例")
Room.shower()
r1 = Room('别墅','alex',10,10)
r1.shower()  #这么调用也没有问题
#报错,因为不是静态方法,必须要实例化
Room.test()

运行结果:

洗澡
洗澡
Traceback (most recent call last):
  File "C:\py\jb51PyDemo\src\Demo\test.py", line 26, in <module>
    Room.test()
TypeError: unbound method test() must be called with Room instance as first argument (got nothing instead)

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

使用python实现简单五子棋游戏

使用python实现简单五子棋游戏

用python实现五子棋简单人机模式的练习过程,供大家参考,具体内容如下 第一次写博客,我尽力把它写好。 最近在初学python,今天就用自己的一些粗浅理解,来记录一下这几天的pytho...

Windows和Linux下使用Python访问SqlServer的方法介绍

经常用Python写demo来验证方案的可行性,最近遇到了Python访问SqlServer的问题,这里总结下。 一、Windows下配置Python访问Sqlserver 环境:Win...

对python插入数据库和生成插入sql的示例讲解

如下所示: #-*- encoding:utf-8 -*- import csv import sys,os import pymysql def read_csv(filen...

Python3使用xml.dom.minidom和xml.etree模块儿解析xml文件封装函数的方法

总结了一下使用Python对xml文件的解析,用到的模块儿如下: 分别从xml字符串和xml文件转换为xml对象,然后解析xml内容,查询指定信息字段。 from xml.dom.m...

Python 串口读写的实现方法

Python 串口读写的实现方法

1.安装pyserial https://pypi.python.org/pypi/pyserial Doc:http://pythonhosted.org/pyserial/ 使用Py...