博客
关于我
Python中的类属性、类方法
阅读量:329 次
发布时间:2019-03-04

本文共 2558 字,大约阅读时间需要 8 分钟。

Python中的类属性与方法

在Python中,类是模板,用于创建实例。类属性和实例属性在设计和使用时有显著的区别。本文将详细探讨Python中的类属性以及类属性与实例属性的区别。

类属性的定义与使用

类属性是直接绑定在类上的属性。相比于实例属性,类属性对于所有实例是共享的。以下是一个简单的例子:

class Person(object):    address = 'Earth'  # 类属性定义在类中    def __init__(self, name):        self.name = name  # 实例属性定义在__init__方法中

通过访问Person.address,可以直接获得类属性的值:

print(Person.address)  # 输出: Earth

实例可以访问类属性,但不会修改类属性:

p1 = Person('Bob')p2 = Person('Alice')print(p1.address)   # 输出: Earthprint(p2.address)   # 输出: Earth

类属性是动态的,可以在运行时修改:

Person.address = 'China'  # 修改类属性print(p1.address)        # 输出: Chinaprint(p2.address)        # 输出: China

类属性与实例属性的冲突

当实例属性和类属性名称相同时,实例属性会优先被访问:

class Person(object):    address = 'Earth'    def __init__(self, name):        self.name = namep1 = Person('Bob')print(p1.address)  # 输出: Earth(因为p1没有实例属性address)p1.address = 'China'  # 给p1实例添加实例属性addressprint(p1.address)  # 输出: Chinaprint(Person.address)  # 输出: Earth(类属性未被修改)

删除实例属性后,可以恢复类属性:

del p1.addressprint(p1.address)  # 输出: Earth

Python中的方法也是属性

在Python中,类中的方法实际上是实例属性,指向函数对象:

class Person(object):    def __init__(self, name, score):        self.name = name        self.score = score    def get_grade(self):        return 'A'p1 = Person('Bob', 90)print(p1.get_grade)  # 输出: 
.
at 0x...>print(p1.get_grade()) # 输出: A

方法可以通过装饰器动态绑定到实例:

import typesdef fun_getGrade(self):    if self.score >= 90:        return 'A'    if self.score >= 60:        return 'B'    return 'C'class Person(object):    address = 'Earth'    def __init__(self, name, score):        self.name = name        self.score = score    p1 = types.MethodType(fun_getGrade, Person)    p1.get_grade = types.MethodType(fun_getGrade, p1)print(p1.get_grade())  # 输出: Ap2 = Person('Alice', 80)print(p2.get_grade())  # 输出: AttributeError: 'Person' object has no attribute 'get_grade'

类方法的定义与使用

类方法可以通过装饰器绑定到类:

class Person(object):    count = 0    def __init__(self, name):        self.name = name        Person.count += 1    @classmethod    def num(cls):        return cls.countprint(Person.num())  # 输出: 0p1 = Person('ZYP')print(Person.num())  # 输出: 1p2 = Person('ZYP2')print(Person.num())  # 输出: 2

类方法可以访问类属性,但不能访问实例属性:

class Person(object):    __count = 0    def __init__(self, name):        self.name = name        Person.__count += 1    @classmethod    def num(cls):        return cls.__countprint(Person.num())  # 输出: 0p1 = Person('ZYP')print(Person.num())  # 输出: 1p2 = Person('ZYP2')print(Person.num())  # 输出: 2

总结

类属性和实例属性在Python中有明显的区别。类属性是共享的,而实例属性各自独立。当类属性和实例属性名称冲突时,实例属性优先级高。类方法可以通过装饰器绑定到类,而实例方法则绑定到实例。理解这些概念是掌握Python对象模型的关键。

转载地址:http://jodh.baihongyu.com/

你可能感兴趣的文章
numpy 用法
查看>>
Numpy 科学计算库详解
查看>>
Numpy.fft.fft和numpy.fft.fftfreq有什么不同
查看>>
numpy.linalg.norm(求范数)
查看>>
Numpy.ndarray对象不可调用
查看>>
Numpy.VisibleDeproationWarning:从不整齐的嵌套序列创建ndarray
查看>>
Numpy:按多个条件过滤行?
查看>>
Numpy:条件总和
查看>>
numpy、cv2等操作图片基本操作
查看>>
numpy中的argsort的用法
查看>>
NumPy中的精度:比较数字时的问题
查看>>
numpy判断对应位置是否相等,all、any的使用
查看>>
Numpy多项式.Polynomial.fit()给出的系数与多项式.Polyfit()不同
查看>>
Numpy如何使用np.umprod重写range函数中i的python
查看>>
numpy学习笔记3-array切片
查看>>
numpy数组替换其中的值(如1替换为255)
查看>>
numpy数组索引-ChatGPT4o作答
查看>>
numpy最大值和最大值索引
查看>>
NUMPY矢量化np.prod不能构造具有超过32个操作数的ufunc
查看>>
Numpy矩阵与通用函数
查看>>