1-15类

 

类:面向对象

In [1]:
class people :
    '帮助信息:'
    #所有实例都会共享
    number=100
    #构造函数,初始化的方法,当创建一个类的时候,首先会调用他 注意:下划线是2个
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def display(self):
        print('number=:',people.number)
    def display_name(self):
        print(self.name)
In [2]:
people.__doc__
Out[2]:
'帮助信息:'
In [3]:
p1=people('tangyudi',30)
In [4]:
p2=people('python',40)
In [5]:
p1.name
Out[5]:
'tangyudi'
In [6]:
p2.name
Out[6]:
'python'
In [7]:
p1.display()
 
number=: 100
In [8]:
p2.display()
 
number=: 100
In [9]:
p2.name='hello'#更改
p2.name
Out[9]:
'hello'
In [10]:
del p2.name#删除
p2.name#删除后就无法再显示,所以报错
 
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-10-e8841ab000e8> in <module>()
      1 del p2.name#删除
----> 2p2.name

AttributeError: 'people' object has no attribute 'name'
In [11]:
hasattr(p1,'name')#hasattr是对属性检测是否存在,返回BOOL
Out[11]:
True
In [12]:
hasattr(p1,'sex')
Out[12]:
False
In [13]:
getattr(p1,'name')#获取属性所对应的值
Out[13]:
'tangyudi'
In [16]:
setattr(p1,'name','marujaio')#更改属性所对应的值
In [17]:
delattr(p1,'name')#删除属性
In [18]:
getattr(p1,'name')
 
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-18-9225ee5d4e45> in <module>()
----> 1getattr(p1,'name')#获取属性所对应的值

AttributeError: 'people' object has no attribute 'name'

猜你喜欢

转载自www.cnblogs.com/AI-robort/p/11627121.html