zoukankan      html  css  js  c++  java
  • python(对象与实例属性)

    类的作用域问题

    由引用(.)才是局部的,类内部的作用域不会超出类体,没有引用(.)是全局的

    # -*- 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__)
    

      

  • 相关阅读:
    数据库MySQL调优实战经验总结
    Apache常见功能实战详解
    使用HeartBeat实现高可用HA的配置过程详解
    Nginx实现集群的负载均衡配置过程详解
    CentOS系统通过PXE实现批量无人值守安装
    CentOS 7 网卡命名修改为eth0格式
    Nagios 系统监控基本安装配置过程详解
    LAMP 系统服务搭建过程详解
    使用 python 管理 mysql 开发工具箱
    C++标准库string类型的使用和操作总结
  • 原文地址:https://www.cnblogs.com/2018-1025/p/12019545.html
Copyright © 2011-2022 走看看