与Java概念一致
2类定义与访问
class类名([父类列表]):
""类注释"""
类体
(Python支持函数重载但是不支持方法重载)
#定义一个类,类中包含两个方法
class fish(object):
count = 0
def swim(self):#swim就是fish中定义的方法
print("i can swiming")
def eat(self):
print("i can eat")
crap = fish()#实例化对象
crap.swim()#对象调用方法
crap.eat()
i can swiming
i can eat
class fish(object):
def __init__(self,fish_name):#定义构造方法
self.name=fish_name #
print("我是构造方法")
def swim(self):
print("i can swiming")
def eat(self):
print("i can eat")
def get_name(self):
print("我的名字叫%s"%self.name)
grass_crap=fish("草鱼")#创建一个草鱼对象
grass_crap.swim()
grass_crap.get_name()
我是构造方法
i can swiming
我的名字叫草鱼
class fish(object):
def __init__(self,name):
self.name = name
def swim(self):
print("%s can swiming"%self.name)
def __del__(self):
print("%s 的函数"%self.name)
grass_crap=fish("超级难")
grass_crap.swim()
鱼 can swiming
鱼 的函数
1.#断言
list_num =[1,2,3,4,5]
def chang_value(list_num,index,value):
if type(list_num) !=list:
return
# if index < 0 or index >= len(list_num):
# return
assert index >=0 and index <len(list_num)
list_num[index]=value
chang_value(list_num,0,99)
print(list_num)
[99, 2, 3, 4, 5]
2.实现两数相加
return 可以返回一个或多个值,以元组(tuple)形式返回
def get_sum(a,b):
result = a+b
return a,b,result,"hell0"
tuple = get_sum(10,20)
(10, 20, 30, ‘hell0’)
3.返回 1+20 2+20 3+30
def get_sum(a,b=20):
result = a+b
return result
num1 = get_sum(1)
num2 = get_sum(2)
num3 = get_sum(3)
print(num2,num1,num3)
22 21 23
: https://blog.csdn.net/Strive_0902/article/details/105325065?
class Parents(object):
def __init__(self,name):
self.name=name
print("I am parents")
def eat(self):
print("I can eat")
class child(Parents):
def __init__(self,cname):
self.cname=cname
print("I am a child")
def jump(self):
print(" i can jump")
child1=child("李红")
child1.jump()
child1.eat()
i can jump
I can eat
Python支持多继承,意味着一个子类可以继承多个父类
class monther(object):
def monther_skill(self):
print("monther can eat")
class father(object):
def father_skill(self):
print("father can eat")
class child(father,monther):
pass
child1=child()
child1.monther_skill()
monther can eat
father can eat
class child(Parents):
def __init__(self,cname):
self.cname=cname
print("I am a child")
def jump(self):
print(" i can jump")
def eat(self):
print(" child can eating")
i can jump
child can eating
1)使用type查看指定对象的类型信息a = 2.1
b = [11,22]
print(type(a))#返回的时指定对象的类型名称一》
-》
if type(a) == float
“”"
2)对于类继承关系来说,使用type()就有点不方便。我们要判断class的类型,可以使用isinstance()函数
class father(object):
def father_skill(self):
print(" i an a father")
class son(father):
pass
class xson(son):
pass
a=son()
b=xson()
print(isinstance(a,son))#true
print(isinstance(a,father))#true
print(isinstance(b,father))#true
3)dir函数
如果要获得一个对象的所有属性和方法,可以使用dir()函数,他返回一个包含字符串的list。比如,获得一个list对象的所有属性和方法: