python中类的属性和方法介绍

yipeiwu_com7年前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)

相关文章

Pytorch中accuracy和loss的计算知识点总结

这几天关于accuracy和loss的计算有一些疑惑,原来是自己还没有弄清楚。 给出实例 def train(train_loader, model, criteon, optimi...

Python中dict和set的用法讲解

Python中dict和set的用法讲解

dict Python内置了字典:dict的支持,dict全称dictionary,在其他语言中也称为map,使用键-值(key-value)存储,具有极快的查找速度。 举个例子,假设要...

Python 实现遥感影像波段组合的示例代码

Python 实现遥感影像波段组合的示例代码

最近要做个遥感相关的小系统,需要波段组合功能,网上找了可以使用ArcGIS安装时自带的arcpy包,但是Python3.7不能使用现有ArcGIS10.2版本,也不想再装其他版本,所以只...

python实现对列表中的元素进行倒序打印

python实现对列表中的元素进行倒序打印

1.案例要求: """有列表["a", "d", "f", "j","z","Z","1"],对列表进行倒序,打印结果为["1","Z","z","j","f","d",""a]""...

Python回文字符串及回文数字判定功能示例

本文实例讲述了Python回文字符串及回文数字判定功能。分享给大家供大家参考,具体如下: 所谓回文字符串,就是一个字符串,从左到右读和从右到左读是完全一样的。回文数字也是如此。 pyth...