第一范文网 - 专业文章范例文档资料分享平台

python类和对象

来源:用户分享 时间:2025/6/11 7:38:37 本文由loading 分享 下载这篇文档手机版
说明:文章内容仅供预览,部分内容可能不全,需要完整文档或者需要复制内容,请下载word后使用。下载word有问题请添加微信号:xxxxxxx或QQ:xxxxxx 处理(尽可能给您提供完整文档),感谢您的支持与谅解。

一、 类和对象的概念 对象=属性+行为(方法)

把具有相同属性和方法的对象归为一类。 类是对象的抽象化,对象是类的实例化。 二、 类的定义、实例化、属性和方法的调用 class 类名: 属性

方法 >>> class people: name='jim' age=20

def printName(self):

print self.name

>>> people.name 'jim' >>> people.p

Traceback (most recent call last): File \ people.p

AttributeError: class people has no attribute 'p' >>> people.printName()

Traceback (most recent call last): File \ people.printName()

TypeError: unbound method printName() must be called with people instance as first argument (got nothing instead) >>> people.printName(self)

Traceback (most recent call last): File \ people.printName(self)

NameError: name 'self' is not defined >>> p=people() >>> p.name 'jim' >>> p.age 20

>>> p.printName() jim

>>> class people1:

__name='mike' __age=20 sex='wemom'

>>> p1=people1() >>> p1.__name

Traceback (most recent call last):

File \ p1.__name

AttributeError: people1 instance has no attribute '__name' >>> p1.__age

Traceback (most recent call last):

File \ p1.__age

AttributeError: people1 instance has no attribute '__age' >>> p1.sex 'wemom' >>> p1.sex 'wemom'

类的内置函数 class c1: def tell(self):

print \

def __init__(self):

print \

def __del__(self):

print \

>>> c11=c1() c1 is init >>> >>> c11=0 c1 is del

三、 类属性、实例属性、类方法、实例方法、静态方法>>> class people: name='alice' __age=13

>>> p=people() >>> p.name 'alice' >>> p.__age

Traceback (most recent call last):

File \ p.__age

AttributeError: people instance has no attribute '__age' 实例对象可以调用类里面定义的公有属性,不能调用私有属性。

>>> people.name 'alice'

>>> people.__age

Traceback (most recent call last):

File \ people.__age

AttributeError: class people has no attribute '__age' >>>类对象可以调用类里面定义的公有属性,不能调用私有属性。

>>> p.sex='man' #sex是实例属性

搜索更多关于: python类和对象 的文档
python类和对象.doc 将本文的Word文档下载到电脑,方便复制、编辑、收藏和打印
本文链接:https://www.diyifanwen.net/c77qbv6fc5q570pk9t1v3_1.html(转载请注明文章来源)
热门推荐
Copyright © 2012-2023 第一范文网 版权所有 免责声明 | 联系我们
声明 :本网站尊重并保护知识产权,根据《信息网络传播权保护条例》,如果我们转载的作品侵犯了您的权利,请在一个月内通知我们,我们会及时删除。
客服QQ:xxxxxx 邮箱:xxxxxx@qq.com
渝ICP备2023013149号
Top