​ 通常情况下,当我们定义了一个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. BZOJ5058 期望逆序对 【矩乘 + 组合数学 + 树状数组】

    题目链接 BZOJ5058 题解 可以发现任意两个位置\(A,B\)最终位置关系的概率是相等的 如果数列是这样: CCCCACCCCBCCCC 那么最终有\(7\)种位置关系 \((A,B)\) \( ...

  2. jenkins(五)---jenkins添加项目

    一.新建项目 二.配置项目 配置远程仓库:主要目的是从远程仓库拉取代码下来 实时构建 Poll SCM 定期检查 如果源码有变更 就build 否则不build build periodically ...

  3. git<git rebase 修改以前提交过的内容>

      git rebase 使用总结: 使用git rebase 修改以前已经提交的内容 比如要修改之前的commit的 hashcode为:187f869c9d54c9297d6b0b1b4ff47d ...

  4. set.seed(7)什么意思

    以前虽然在每个程序都看见过,但是没注意过这个问题,也不理解是什么意思,去搜了一些帖子才明白. 其实,很好理解,就是如果你不加set.seed(7),当然代码也可以执行这个命令,但是每次执行的结果都会不 ...

  5. ubuntu vim 配置

    set nuset autoindent cindentmap<F9> :w<cr> :!g++ -O2 -o %< % -Wall<cr>map<F1 ...

  6. java 锁的分类

    java中为了解决多线程并发带来的线程安全问题,引入了锁机制. 一.公平锁和非公平锁 1.公平锁:按照申请锁的顺序(FIFO队列)来获取锁. 2.非公平锁:所有线程都会竞争,获取的锁的顺序和申请顺序无 ...

  7. Kafka 0.8 Producer处理逻辑

    Kafka Producer产生数据发送给Kafka Server,具体的分发逻辑及负载均衡逻辑,全部由producer维护. 1.Kafka Producer默认调用逻辑 1.1 默认Partiti ...

  8. bzoj千题计划132:bzoj1189: [HNOI2007]紧急疏散evacuate

    http://www.lydsy.com/JudgeOnline/problem.php?id=1189 二分答案 源点向人连边,流量为1 门拆为mid个点,同一个门的第j个点向第j+1个点连边,流量 ...

  9. idea 安装lombok 插件过程

    一.作用 Lombok是一个可以通过简单的注解的形式来帮助我们简化消除一些必须有但显得很臃肿的 Java 代码的工具,bean,entity等类,绝大部分数据类类中都需要get.set.toStrin ...

  10. Redis学习四:解析配置文件 redis.conf

    一.它在哪 地址: 思考:为什么要将它拷贝出来单独执行? 二.Units单位 1 配置大小单位,开头定义了一些基本的度量单位,只支持bytes,不支持bit 2 对大小写不敏感 三.INCLUDES包 ...