类的作用域问题
由引用(.)才是局部的,类内部的作用域不会超出类体,没有引用(.)是全局的
# -*- coding: utf-8 -*- wheel='轮子' class car: '这是一个车的类' #类的说明 wheel='橡胶' Engine='发动机' def __init__(self,License,brand,price): #初始化必须这么些(__init__),自动return #产生self字典 self.Licenses=License self.brands=brand self.prices=price print('我是全局的',wheel,'我是局部的',car.wheel) def transport(self): print('---拉货---') def manned(self): print('---载人---') #带参方法 def colors(self,color): print('---%s的颜色是%s---'%(self.Licenses,color)) car1=car('123456','大众','100000')
修改实例的属性(用实例名)与类的属性(用实例名)区分
# -*- coding: utf-8 -*- class car: '这是一个车的类' #类的说明 wheel='橡胶' Engine='发动机' def __init__(self,License,brand,price): #初始化必须这么些(__init__),自动return #产生self字典 self.Licenses=License self.brands=brand self.prices=price def transport(self): print('---拉货---') def manned(self): print('---载人---') #带参方法 def colors(self,color): print('---%s的颜色是%s---'%(self.Licenses,color)) car1=car('123456','大众','100000') # 改的仅是实例的 car1.wheel='轮子1' print(car.__dict__) print(car1.wheel) # 改的是类的 car.wheel='轮子2' print(car.__dict__)
类体中变量的修改与实例后的修改
# -*- coding: utf-8 -*- class car: '这是一个车的类' #类的说明 wheel='橡胶' Engine='发动机' s=['q','w'] def __init__(self,License,brand,price): #初始化必须这么些(__init__),自动return #产生self字典 self.Licenses=License self.brands=brand self.prices=price def transport(self): print('---拉货---') def manned(self): print('---载人---') #带参方法 def colors(self,color): print('---%s的颜色是%s---'%(self.Licenses,color)) car1=car('123456','大众','100000') #给实例变量重新赋值 # car1.s=[1,2,3] # print(car.s) # print(car1.s) #修改的是类中的变量,不是属性 car1.s.append('e') print(car.s) print(car1.s) print(car1.__dict__)