6.1.1 类定义语法
class Car:
def infor(self):
print("This is a car ")
class Car:
def infor(self):
print("This is a car ")
car = Car()
car.infor()
This is a car
class Car:
def infor(self):
print("This is a car ")
car = Car()
car.infor()
print(isinstance(car,Car))
print(isinstance(car,str))
This is a car
True
False
>>> class A:
... pass
...
>>> def demo():
... pass
...
>>> if 5>3:
... pass
...
>>>
6.1.2 self参数
>>> class A:
... def __init__(hahaha,v):
... hahaha.value = v
... def show(hahaha):
... print(hahaha.value)
...
>>> a = A(3)
>>> a.show()
3
6.1.3 类成员与实例成员
class Car:
price = 10000 #定义类属性
def __init__(self,c):
self.color = c #定义实例属性
car1 = Car("Red") #实例化对象(car1就是self成员)
car2 = Car("Blue")
print(car1.color,Car.price) #查看实例属性和类属性的值
Car.price = 11000 #修改类属性
Car.name = 'QQ' #动态增加类属性
car1.color = "Yellow" #修改实例属性
print(car2.color,Car.name,Car.price)
print(car1.color,Car.name,Car.price)
运行结果:
Red 10000
Blue QQ 11000
Yellow QQ 11000
如何把普通函数转化为成员方法:
import types
def setSpeed(self,s):
self.speed = s
car1.setSpeed = types.M ethodType(setSpeed,car1) #动态增加成员方法
car1.setSpeed(50) #调用成员方法
print(car1.speed)
>>> import types
>>> class Person(object):
... def __init__(self,name):
... assert isinstance(name,str),'name must be string'
... self.name = name
...
>>> def sing(self):
... print(self.name+'can sing.')
...
>>> def walk(self):
... print(self.name+'can walk.')
...
>>> def eat(self):
... print(self.name+'can eat.')
...
>>> zhang = Person('zhang')
>>> zhang.sing() #用户不具有该行为
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'Person' object has no attribute 'sing'
>>> zhang.sing = types.MethodType(sing,zhang) #动态增加一个新行为
>>> zhang.sing()
zhangcan sing.
>>> zhang.walk()
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'Person' object has no attribute 'walk'
>>> zhang.walk = types.MethodType(walk,zhang) #动态增加一个新行为
>>> zhang.walk()
zhangcan walk.
>>> del zhang.walk #删除用户行为
>>> zhang.walk()
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'Person' object has no attribute 'walk'
>>>
>>> class Demo:
... pass
...
>>> t = Demo()
>>> def test(self,v):
... self.value = v
...
>>> t.test = test
>>> t.test #普通函数
>>> t.test(t,3) #必须为self参数传值
>>> t.test = types.MethodType(test,t)
>>> t.test #绑定的方法
>
>>> t.test(5) #不需要为self参数传值