​ 通常情况下,当我们定义了一个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. spark 性能调优(一) 性能调优的本质、spark资源使用原理、调优要点分析

    转载:http://www.cnblogs.com/jcchoiling/p/6440709.html 一.大数据性能调优的本质 编程的时候发现一个惊人的规律,软件是不存在的!所有编程高手级别的人无论 ...

  2. fzyzojP2291 -- 小添添的庄园之道路修复

    直接换根dp f[i]表示,i为根的子树的方案 f[i]=Π(f[son]+1)(就是考虑这个边修不修(不修,子树中只有一种方案)) 这里是乘法 换根的时候,直接算的话,为了消除x对fa的贡献,要乘上 ...

  3. centos详细安装redis步骤

    1. 从官网(http://redis.io)下载最新稳定版2. 使用命令解压下载的tar包:tar –zxvf redis-3.2.0.tar.gz3. 通过命令cd redis-3.2.0进入源码 ...

  4. C++ std::allocator<T> 与new对比效率使用

    基础知识通道:http://blog.csdn.net/Xiejingfa/article/details/50955295 C/C++: #include <iostream> #inc ...

  5. bzoj 4332 FFT型的快速幂(需要强有力的推导公式能力)

     有n个小朋友,m颗糖,你要把所有糖果分给这些小朋友. 规则第 i 个小朋友没有糖果,那么他之后的小朋友都没有糖果..如果一个小朋友分到了 xx 个糖果,那么的他的权值是 f(x) = ox^2 +  ...

  6. 二、Linux学习之centOS的的setup

    因为我是在VMware上安装的centOS,网络设置选择的是桥接模式,这样可以和实体机使用同样的网络,但是也使用同样的IP,因此就需要设置一下IP了,否则使用ifconfig查询ip的时候显示的是12 ...

  7. 【Asp.net入门03】第一个ASP.NET 应用程序-创建ASP.NET项目

    本部分主要内容: 创建并运行Asp.net项目 web窗体 数据模型 调用代码隐藏方法 数据验证 1.操作步骤 第一步:启动Visual Studio 2013,然后从File(文件)菜单中选择New ...

  8. npm安装socket.io时报错的解决方法(npm WARN enoent ENOENT: no such file or directory, open '/usr/local/nodejs/bin/package.json')

    执行 npm install socket.io安装时报错: [root@WEB node_modules]# npm install socket.ionpm WARN enoent ENOENT: ...

  9. [Java]-Java的版本演化

    一.Java SE 8 Java SE 8发行于2014年3月18日,代号culture,这是一个在Java历史上的重大发布 Java SE 8 新特性: Lambda Expressions(Lam ...

  10. Pycharm远程连接服务器,并在本地调试服务器代码

    问题描述 其实有很多教程了,我只是想记录一下设置得记录,这样就能充分利用阿里云服务器为我跑代码了... 步骤一:配置deployment 步骤二:选择远程python解释器 步骤三:将本地文件上传至远 ...