python中类的属性和方法介绍

yipeiwu_com6年前Python基础

Python-类属性,实例属性,类方法,静态方法,实例方法

类属性和实例属性

#coding:utf-8
class Student(object):
  name = 'I am a class variable' #类变量
>>> s = Student() # 创建实例s
>>> print(s.name) # 打印name属性,因为实例并没有name属性,所以会继续查找class的name属性
Student
>>> print(Student.name) # 打印类的name属性
Student
>>> s.name = 'Michael' # 给实例绑定name属性
>>> print(s.name) # 由于实例属性优先级比类属性高,因此,它会屏蔽掉类的name属性
Michael
>>> print(Student.name) # 但是类属性并未消失,用Student.name仍然可以访问
Student
>>> del s.name # 如果删除实例的name属性
>>> print(s.name) # 再次调用s.name,由于实例的name属性没有找到,类的name属性就显示出来了
Student

类方法,实例方法,静态方法

实例方法,第一个参数必须要默认传实例对象,一般习惯用self。

静态方法,参数没有要求。

类方法,第一个参数必须要默认传类,一般习惯用cls。

# coding:utf-8
class Foo(object):
  """类三种方法语法形式"""
 
  def instance_method(self):
    print("是类{}的实例方法,只能被实例对象调用".format(Foo))
 
  @staticmethod
  def static_method():
    print("是静态方法")
 
  @classmethod
  def class_method(cls):
    print("是类方法")
 
foo = Foo()
foo.instance_method()
foo.static_method()
foo.class_method()
print('----------------')
Foo.static_method()
Foo.class_method()

运行结果:

是类<class '__main__.Foo'>的实例方法,只能被实例对象调用
是静态方法
是类方法
----------------
是静态方法
是类方法

类方法

由于python类中只能有一个初始化方法,不能按照不同的情况初始化类,类方法主要用于类用在定义多个构造函数的情况。
特别说明,静态方法也可以实现上面功能,当静态方法每次都要写上类的名字,不方便。

# coding:utf-8
class Book(object):
 
  def __init__(self, title):
    self.title = title
 
  @classmethod
  def class_method_create(cls, title):
    book = cls(title=title)
    return book
 
  @staticmethod
  def static_method_create(title):
    book= Book(title)
    return book
 
book1 = Book("use instance_method_create book instance")
book2 = Book.class_method_create("use class_method_create book instance")
book3 = Book.static_method_create("use static_method_create book instance")
print(book1.title)
print(book2.title)
print(book3.title)

相关文章

Python实现计算文件MD5和SHA1的方法示例

本文实例讲述了Python实现计算文件MD5和SHA1的方法。分享给大家供大家参考,具体如下: 不多说,直接源码: #file md5 import sys; import hash...

python整小时 整天时间戳获取算法示例

根据当前时间戳获得整小时时间戳 unit = 3600 start_time = int(time.time())/3600 * 3600 根据当前时间戳获得整天时间戳 uni...

使用Django的模版来配合字符串翻译工作

Django模板使用两种模板标签,且语法格式与Python代码有些许不同。 为了使得模板访问到标签,需要将 {% load i18n %} 放在模板最前面。 这个{% trans %}模...

python中的逆序遍历实例

如果你需要遍历数字序列,可以使用内置range()函数。它会生成数列。 range()语法: range(start,end,step=1):顾头不顾尾 正序遍历: range(10):...

Python读取视频的两种方法(imageio和cv2)

用python读取视频有两种主要方法,大家可依据自己的需求进行使用。 方法一: 使用imageio库,没有安装的可用pip安装或自己下载,安装好后重启终端即可调用。 import p...