​ 通常情况下,当我们定义了一个class,创建了一个class的实例后,我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性。下来我就讲下添加属性和方法,同时也将下限值添加属性方法。

添加属性

​ 给一个实例添加属性和方法时,只有对象能使用,对类添加方法和属性时,为类属性和类方法

>>> class Peopre(object):
"""docstring for Peopre"""
def __init__(self):
pass ... ... ... ... ...
>>> p=Peopre()
>>> Peopre.__dict__
mappingproxy({'__module__': '__main__', '__doc__': 'docstring for Peopre', '__init__': <function Peopre.__init__ at 0x02B1B6F0>, '__dict__': <attribute '__dict__' of 'Peopre' objects>, '__weakref__': <attribute '__weakref__' of 'Peopre' objects>})
>>> p.__dict__
{} # -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
# 对实例添加属性
>>> p.name='张三'
>>> p.name
'张三'
>>> Peopre.__dict__
mappingproxy({'__module__': '__main__', '__doc__': 'docstring for Peopre', '__init__': <function Peopre.__init__ at 0x02B1B6F0>, '__dict__': <attribute '__dict__' of 'Peopre' objects>, '__weakref__': <attribute '__weakref__' of 'Peopre' objects>}) # -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
# 对类添加属性,添加的为类属性
>>> Peopre.name='name'
>>> Peopre.age='12'
>>> Peopre.__dict__
mappingproxy({'__module__': '__main__', '__doc__': 'docstring for Peopre', '__init__': <function Peopre.__init__ at 0x02B1B6F0>, '__dict__': <attribute '__dict__' of 'Peopre' objects>, '__weakref__': <attribute '__weakref__' of 'Peopre' objects>, 'name': 'name', 'age': '12'}) >>> p1=Peopre()
>>> p1.name
'name'
>>> p1.age
'12'
>>> p.name
'张三'

添加方法

>>> class Peopre(object):
"""docstring for Peopre"""
def __init__(self):
pass
... ... ... ...
>>> def hi():
print("你好")
... ...
>>> Peopre.__dict__
mappingproxy({'__module__': '__main__', '__doc__': 'docstring for Peopre', '__init__': <function Peopre.__init__ at 0x0327E810>, '__dict__': <attribute '__dict__' of 'Peopre' objects>, '__weakref__': <attribute '__weakref__' of 'Peopre' objects>}) # -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
# 添加的方法为类方法
>>> Peopre.hi=hi
>>> Peopre.__dict__
mappingproxy({'__module__': '__main__', '__doc__': 'docstring for Peopre', '__init__': <function Peopre.__init__ at 0x0327E810>, '__dict__': <attribute '__dict__' of 'Peopre' objects>, '__weakref__': <attribute '__weakref__' of 'Peopre' objects>, 'hi': <function hi at 0x0327E858>})
>>> Peopre.hi
<function hi at 0x0327E858>
>>> Peopre.hi()
你好
>>> def hello():
... print("hello!")
...
>>> p = Peopre()
>>> p.hi
<bound method hi of <__main__.Peopre object at 0x032722B0>>
>>> p.hi()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: hi() takes 0 positional arguments but 1 was given # -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
# 添加的为普通方法
>>> p.hello = hello
>>> p.hello()
hello!
>>> p.__dict__
{'hello': <function hello at 0x0327E8A0>}
>>>

删除属性、方法

删除的方法:

  • del 对象.属性名
  • delattr(对象, "属性名")
>>> class Peopre(object):
"""docstring for Peopre"""
def __init__(self, name):
self.name = name
def hi(self):
print("我的名字是:%s"%self.name)
... ... ... ... ... ...
>>> p = Peopre("张三")
>>> p.hi()
我的名字是:张三
>>> p.__dict__
{'name': '张三'}
>>> del(p.name)
>>> p.__dict__
{}
# 删除方法
>>> Peopre.__dict__
mappingproxy({'__module__': '__main__', '__doc__': 'docstring for Peopre', '__init__': <function Peopre.__init__ at 0x02D2E858>, 'hi': <function Peopre.hi at 0x02D2E810>, '__dict__': <attribute '__dict__' of 'Peopre' objects>, '__weakref__': <attribute '__weakref__' of 'Peopre' objects>})
>>> def hello():
... print("你好")
...
>>> Peopre.hello = hello
>>> Peopre.__dict__
mappingproxy({'__module__': '__main__', '__doc__': 'docstring for Peopre', '__init__': <function Peopre.__init__ at 0x02D2E858>, 'hi': <function Peopre.hi at 0x02D2E810>, '__dict__': <attribute '__dict__' of 'Peopre' objects>, '__weakref__': <attribute '__weakref__' of 'Peopre' objects>, 'hello': <function hello at 0x0110D660>})
>>> del(Peopre.hello)
>>> Peopre.__dict__
mappingproxy({'__module__': '__main__', '__doc__': 'docstring for Peopre', '__init__': <function Peopre.__init__ at 0x02D2E858>, 'hi': <function Peopre.hi at 0x02D2E810>, '__dict__': <attribute '__dict__' of 'Peopre' objects>, '__weakref__': <attribute '__weakref__' of 'Peopre' objects>})
>>>

__slots__

​ 限制该class能添加的属性. 但__slots__定义的属性仅对当前类起作用,对继承的子类是不起作用的.

>>> class Peopre(object):
"""docstring for Peopre"""
__slots__ = ("name","age")
... ... ...
>>> p = Peopre
>>> p = Peopre()
>>> p.name= "张三"
>>> p.age= 14
>>> p.height = 170
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Peopre' object has no attribute 'height'
# 对继承的子类是不起作用的
>>> class Test(Peopre):
pass ... ... ...
>>> t = Test()
>>> t.height = 170
>>>

python面向对象(七)属性方法的添加的更多相关文章

  1. python面向对象基础-属性/方法

  2. python 面向对象、特殊方法与多范式、对象的属性及与其他语言的差异

    1.python 面向对象 文章内容摘自:http://www.cnblogs.com/vamei/archive/2012/06/02/2532018.html   1.__init__() 创建对 ...

  3. Python面向对象之内置方法

    1.isinstance(obj,cls)和issubclass(sub,super) isinstance(obj,cls)检查是否obj是否是类 cls 的对象 issubclass(sub, s ...

  4. python静态方法类方法属性方法

    Python的静态方法和类成员方法都可以被类或实例访问,两者概念不容易理清,但还是有区别的: 1)静态方法无需传入self参数,类成员方法需传入代表本类的cls参数: 2)从第1条,静态方法是无法访问 ...

  5. python 面向对象 私有属性

    __init__构造函数 self.name = name # 属性, 实例变量,成员变量,字段 def sayhi()# 方法, 动态属性 私有属性不对外看到 前面加上__ class role() ...

  6. python面向对象之类属性,实例属性

    python中的属性分为类属性和实例属性,之前已经说过一些,这里主要是对类属性与实例属性的增删改查 首先是对类属性的增删改查,下面这个是对类属性的修改,在书写类时,已经对类属性occupation进行 ...

  7. python面向对象内置方法关于属性篇

    1.关于__xxxattr__之__getattr__.__setattr__.__delattr__ 2.关于__xxxitem__之__getitem__.__setitem__.__delite ...

  8. python -- 面向对象编程(属性、方法)

    一.属性 对象的属性(attribute)也叫做数据成员(data member). 如果想指向某个对象的属性,可以使用格式: object.attribute 属性又分为:私有属性和公有属性. 私有 ...

  9. Python面向对象之魔术方法

    __str__ 改变对象的字符串显示.可以理解为使用print函数打印一个对象时,会自动调用对象的__str__方法 class Student: def __init__(self, name, a ...

随机推荐

  1. C#线程篇---线程池如何管理线程(6完结篇)

    C#线程基础在前几篇博文中都介绍了,现在最后来挖掘一下线程池的管理机制,也算为这个线程基础做个完结. 我们现在都知道了,线程池线程分为工作者线程和I/O线程,他们是怎么管理的? 对于Microsoft ...

  2. poj 2396 Budget

    一个m行n列的矩阵,给出每行每列中元素的和,以及对一些格子的大小限制,求一个可行方案,输出矩阵. 大小限制形如:严格大于i,严格小于i,等于i. 1<=m<=200.1<=n< ...

  3. 一、linux学习之centOS系统安装(VMware下安装)

    一.下载 这个真的没有什么技术含量,也不附下载连接了.这里需要说明的是,其实在VMware下安装centOS是非常简单的,但是这里我要纪录的是在PC上安装centOS,之所以跟标题有出入是因为为了纪录 ...

  4. Nginx Upstream Keepalive 分析 保持长连接

    Nginx Upstream长连接由upstream模式下的keepalive指令控制,并指定可用于长连接的连接数,配置样例如下: upstream http_backend {     server ...

  5. Kubernetes init container

    目录 简介 配置 init container与应用容器的区别 简介 在很多应用场景中,应用在启动之前都需要进行如下初始化操作: 等待其他关联组件正确运行(例如数据库或某个后台服务) 基于环境变量或配 ...

  6. Java基础-IO流对象之内存操作流(ByteArrayOutputStream与ByteArrayInputStream)

    Java基础-IO流对象之内存操作流(ByteArrayOutputStream与ByteArrayInputStream) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.内存 ...

  7. day11 细节记忆

    单一职责:一个方法只做一件事. 值传递——java只有值传递. gender(性别) male(男)female(女) 自动生成的set.get方法中,布尔类型的get方法需要手工改为get(默认是i ...

  8. C语言中的指针和内存泄漏几种情况

    引言 原文地址:http://www.cnblogs.com/archimedes/p/c-point-memory-leak.html,转载请注明源地址. 对于任何使用C语言的人,如果问他们C语言的 ...

  9. java 编码问题

    Java默认使用Unioncode编码,即不论什么语言都是一个字符占两个字节 Java的class文件编码为UTF-8,而虚拟机JVM编码为UTF-16 UTF-8编码下,一个中文占3个字节,一个英文 ...

  10. 洛谷 P3382 【模板】三分法

    https://www.luogu.org/problem/show?pid=3382 题目描述 如题,给出一个N次函数,保证在范围[l,r]内存在一点x,使得[l,x]上单调增,[x,r]上单调减. ...