《零基础入门学习Python》学习过程笔记【39类的其他内容】

来源:互联网 发布:seo研究中心新浪微博 编辑:程序博客网 时间:2024/06/05 05:17

1什么是组合?

把类的对象放在一个新类里面

class A:    def __init__(self,x):        self.n=xclass B:    def __init__(self,x):        self.n=xclass C:    def __init__(self):        self.a=A(1)        self.b=B(2)        print(self.a.n)        print(self.b.n)
>>> c=C()12


2
>>> class A:n=1>>> a=A()>>> a.n=10>>> a.n 10    #直接改变了内部属性的值


3.通过类名改变属性的值会发生什么?

>>> class A:n=1
下面这段程序很正常
>>> a=A()>>> b=A()>>> c=A()>>> a.n1>>> b.n1>>> c.n1
下面这段程序很正常
>>> a.n=2>>> a.n2>>> b.n1>>> c.n1

下面这段程序不太正常

>>> A.n=10>>> a.n2>>> b.n10>>> c.n10
为什么a.n没有改变?对象本身的属性覆盖了类的属性



5.对 对象中没有的变量赋值会出现什么情况?会添加这个属性

>>> class C:a=1>>> c=C()>>> c.b=1>>> c.a1>>> c.b1


4.属性的名字和方法的名字相同会出现什么情况?

后面的会覆盖前面的

>> c=C()>>> c.x<bound method C.x of <__main__.C object at 0x040C8BF0>> (没有变量x,只有函数x)>>> c.x()哈哈


>>> class C:def x(self):print("哈哈")x=1>>> c=C()>>> c.x1
>>> c.x()Traceback (most recent call last):  File "<pyshell#66>", line 1, in <module>    c.x()TypeError: 'int' object is not callable     (没有函数x只有变量x)


特殊的情况:如果在外面为该变量起与方法同名的变量(为该变量名赋值),该函数会被覆盖

5.如何查看对象的属性? 对象名.__dict__

>>> class A:x=1>>> a=A()>>> a.y=2>>> a.__dict__{'y': 2}

6.什么是绑定?

当对象为该类中的变量赋值时,它的属性中才有他们的内容。在对象的外部对对象的属性中没有的变量赋值(添加属性)也算。






阅读全文
0 0