博客
关于我
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/

你可能感兴趣的文章
php的几种运行模式CLI、CGI、FastCGI、mod_php
查看>>
php的四大特性八大优势
查看>>
RabbitMQ
查看>>
PHP的威胁函数与PHP代码审计实战
查看>>
PHP的引用举例
查看>>
PHP相关代码
查看>>
RabbitMQ
查看>>
php知识点记录
查看>>
PHP知识笔记:CGI, FastCGI, PHP-CGI, PHP-FPM, Spawn-FCGI区别
查看>>
PHP第三方登录—OAuth2.0协议
查看>>
php筛选js,php如何多条件筛选js代码
查看>>
R730服务器做了raid的硬盘,插在R720上面可以用吗?
查看>>
PHP类数组式访问(ArrayAccess接口)
查看>>
PHP系列:浅谈PHP中isset()和empty() 函数的区别
查看>>
PHP索引数组unset的坑-array_values解决方案
查看>>
PHP索引数组排序方法整理(冒泡、选择、插入、快速)
查看>>
PHP线程安全和非线程安全
查看>>
R3LIVE开源项目常见问题解决方案
查看>>
php缃戠珯,www.wfzwz.com
查看>>
php缓存查询函数
查看>>