python虽然简单,依旧具有面向对象的三个特性……
file:
class Turtle:
color='green'
weight=10
def climb(self):
print("我要一步一步往上爬")
shell >>> tt=Turtle()
>>> tt.climb
<bound method Turtle.climb of <__main__.Turtle object at 0x000001D2FEBC3A90>>
>>> tt.climb()
我要一步一步往上爬
>>> print(tt.color)
green
>>> class Mylist(list):
pass
>>> list2=Mylist()
>>> list2.append(2)
>>> list2
[2]
>>> list2.append(1)
>>> list2.sort()
>>> list2
[1, 2]
>>> class S:
def fun(self):
print('s')
>>> class b:
def fun(self):
print('b')
>>> a=S()
>>> B=b()
>>> a.fun()
s
>>> B.fun()
b
其中self相当于c++中的this指针
class ball:
def setName(self,name):
self.name=name
def kick(self):
print('who?')
>>> a=ball()
>>> a.setname('a')
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
a.setname('a')
AttributeError: 'ball' object has no attribute 'setname'
>>> a.setName('a')
>>> print(a.name)
a
python的魔法方法之 __init__
可以认为是构造函数
class Ball:
def __init__(self,name):
self.name=name
def kick(self):
print('i am %s '% self.name)
>>> b=Ball('misszhou')
>>> b.kick()
i am misszhou
共有与私有数据
默认对象属性方法是共有的,用"."即可访问
__即为私有的
class Person:
__name='misszhou'
def getName(self):
return self.__name
>>> p=Person()
>>> p.__name
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
p.__name
AttributeError: 'Person' object has no attribute '__name'
>>> p.getName()
'misszhou'
>>> p.__Person__name
SyntaxError: unexpected indent
>>> p._Person__name
'misszhou'
继承
class Parent:
def hello(self):
print('parent')
>>> class Child(Parent):
pass
>>> p=Parent()
>>> p.hello()
parent
>>> c=Child()
>>> c.hello()
parent
子类可以覆盖父类同名方法
class Child(Parent):
def hello(self):
print('child')
>>> c=Child()
>>> c.hello()
child
使用未绑定的父类实例对象 import random as r
class Fish:
def __init__(self):
self.x=r.randint(0,10)
self.y=r.randint(0,10)
def move(self):
self.x-=1
print('pos:',self.x,self.y)
class GoldFish(Fish):
pass
class Carp(Fish):
pass
class Salmon(Fish):
pass
class Spark(Fish):
def __init__(self):
self.hungry=True#只写这句话就没有xy啦
Fish.__init__(self)
def eat(self):
if self.hungry:
print('eat')
self.hungry=False
else:
print('not eat')
使用super函数 class Spark(Fish):
def __init__(self):
self.hungry=True#只写这句话就没有xy啦
#Fish.__init__(self)
super().__init__() #多重继承就更方便了
def eat(self):
if self.hungry:
print('eat')
self.hungry=False
else:
print('not eat')
python支持多重继承
只需要在括号中写就可以啦
>>> class Base1:
def fool(self):
print('1')
>>> class Base2:
def foo2(self):
print('2')
>>> class C(Base1,Base2):
pass
>>> c=C()
>>> c.foo()
Traceback (most recent call last):
File "<pyshell#73>", line 1, in <module>
c.foo()
AttributeError: 'C' object has no attribute 'foo'
>>> c.fool()
1
>>> c.foo2()
2
组合
把类的实例化放到新类里面
class Turtle:
def __init__(self,x):
self.num=x
class Fish:
def __init__(self,x):
self.num=x
class Pool:
def __init__(self,x,y):
self.turtle=Turtle(x)
self.fish=Fish(y)
def printout(self):
print("turtle:%d,fish:%d"% (self.turtle.num,self.fish.num))
>>> pool=Pool(4,5)
>>> pool.printout()
turtle:4,fish:5
类,类对象,实例对象
>>> class C:
count=0
>>> a=C()
>>> b=C()
>>> a.count
0
>>> b.count
0
>>> a.count+=10
>>> a.count
10
>>> b.count
0
>>> C.count+=100
>>> a.count
10
>>> b.count
100
>>> c=C()
>>> c.count
100
a的属性只是对象属性 >>> class C:
def x(self):
print("x-man")
>>> c=C()
>>> c.x()
x-man
>>> c.x=1
>>> c.x
1
>>> c.x()
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
c.x()
TypeError: 'int' object is not callable
所以要注意属性名字和方法名字
>>> class BB:
def printbb():
print('no zuo no die')
>>> BB.printbb()
no zuo no die
>>> bb=BB()
>>> bb.printbb()
Traceback (most recent call last):
File "<pyshell#33>", line 1, in <module>
bb.printbb()
TypeError: printbb() takes 0 positional arguments but 1 was given<pre name="code" class="python">>>> issubclass(C,C)
True
>>> issubclass(C,object)
True
>>> class CC:
def setXY(self,x,y):
self.x=x
self.y=y
def printXY(self):
print(self.x,self.y)
>>> dd=CC()
>>> dd.__dict__
{}
>>> CC.__dict__
mappingproxy({'printXY': <function CC.printXY at 0x000001934E4A6D90>, '__weakref__': <attribute '__weakref__' of 'CC' objects>, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'CC' objects>, 'setXY': <function CC.setXY at 0x000001934E4A6D08>, '__doc__': None})
>>> dd.setXY(4,5)
>>> dd.__dict__
{'x': 4, 'y': 5}
>>> CC.__dict__
mappingproxy({'printXY': <function CC.printXY at 0x000001934E4A6D90>, '__weakref__': <attribute '__weakref__' of 'CC' objects>, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'CC' objects>, 'setXY': <function CC.setXY at 0x000001934E4A6D08>, '__doc__': None})
>>> del CC
>>> ee=CC()
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
ee=CC()
NameError: name 'CC' is not defined
>>> dd.printXY()
4 5
与类/对象有关的内置函数
issubclass(class,classinfo)第二个参数可以是元组,只要有一个是前面的子类就返回true
>>> class A返回
pass
>>> class C(A):
pass
>>> issubclass(C,C)
True
>>> issubclass(C,object)
True
isinstance(object,classinfo)
如果第一个参数不是类,永远返回false;如果第二个参数不是类对象或是类对象组成的元组,返回typeerror异常
>>> c1=C()
>>> isinstance(c1,C)
True
>>> isinstance(c1,(C,A))
True
>>> isinstance(c1,A)
True
hasattr(object,name)测试对象是否有指定的属性
>>> class C:
def __init__(self,x=0):
self.x=x
>>> c1=C()
>>> hasattr(c1,'x')
True
getAttr 返回属性值
>>> getattr(c1,'x')
0
>>> getattr(c1,'y','no attr')
'no attr'
setattr delattr
>>> getattr(c1,'y','no attr')
'no attr'
>>> setattr(c1,'y','fishc')
>>> getattr(c1,'y')
'fishc'
>>> delattr(c1,'y') >>> getattr(c1,'y','no attr')
'no attr'
property(获得属性,设置属性,删除属性)三个函数自己写
class C:
def __init__(self,size=10):
self.size=size
def getSize(self):
return self.size
def setSize(self,value):
self.size=value
def delSize(self):
del self.size
x=property(getSize,setSize,delSize)
>>> c1=C()
>>> c1.getSize()
10
>>> c1.x
10
>>> c1.x=18
>>> c1.getSize()
18
>>> c1.size
18
>>> del c1.x
>>> c1.size
Traceback (most recent call last):
File "<pyshell#114>", line 1, in <module>
c1.size
AttributeError: 'C' object has no attribute 'size'