zoukankan      html  css  js  c++  java
  • Python 面向对象3-类变量与实例变量

     1 #!/usr/bin/env python
     2 # -*- coding:utf-8 -*-
     3 # 作者:Presley
     4 # 邮箱:1209989516@qq.com
     5 # 时间:2018-08-05
     6 # OOP学习1
     7 
     8 class Role(object):
     9     members = 0
    10     ac = None
    11     def __init__(self,name,role,weapon,life_value=100,money=15000):
    12         self.name = name
    13         self.role = role
    14         self.weapon = weapon
    15         self.life_value = life_value
    16         self.money = money
    17         self.aaa = 1
    18         Role.members += 1#每增加一个实例则members值加1
    19     def shot(self):
    20         print("shooting...")
    21 
    22     def got_shot(self):
    23         print("ah...,I got shot...")
    24 
    25     def buy_gun(self,gun_name):
    26         print("just bought {0}".format(gun_name))
    27         self.gun_name = gun_name
    28         print(self.aaa)
    29         print(self.ac)
    30 
    31 #在没有实例化之前是不能调实例化中的属性的但是可以掉用类中的属性
    32 print(Role.ac)#能打印
    33 #print(Role.weapon)#报错,显示没有weapon,因为没有实例化
    34 
    35 
    36 #Role的实例
    37 #把一个抽象的类变成一个具体的对象的过程
    38 r1 = Role("wohaoshuai1","police","AK47")#生成一个角色
    39 #相当于Role(p1,"wohaoshuai","police","AK47")
    40 
    41 r2 = Role("wohaoshuai2","police","B22") #生成一个角色
    42 print("r2",r2.ac,r2.weapon,Role.members)
    43 
    44 r3 = Role("wohaoshuai3","police","AK47")
    45 
    46 #r1.buy_gun("AK47") #会自动转换成Role.buy_gun(r1,"AK47")
    47 
    48 
    49 r1.ac = "China Brand"
    50 r2.ac = "US Brand"
    51 
    52 Role.ac = "riben Brand"
    53 Role.weapon = "riben wepon"
    54 
    55 print("r1:",r1.ac,r1.weapon,Role.members)
    56 print("r2",r2.ac,r2.weapon,Role.members)
    57 print("r3",r3.ac,r3.weapon,Role.members)
    58 
    59 '''总结:
    60     1、ac是类的属性
    61     2、weapon是实例属性
    62     3、实例访问方法或属性的时候其实是访问其类的方法或属性,无论一个类中有多少个实例对象,当他们访问对象中的方法或属性的时候都是调用类的方法或属性
    63 '''
  • 相关阅读:
    u-boot 用哪个lds链接脚本
    u-boot-2019.07 移植步骤
    u-boot-2016.09 make编译过程分析(二)
    grep 命令搜索 带空格的字符
    uboot if_changed函数
    2019保险规划 待完善
    MongoDB Capped集合
    并发编程——详解 AQS CLH 锁
    Spring容器中的Bean几种初始化方法和销毁方法的先后顺序
    观察者模式
  • 原文地址:https://www.cnblogs.com/Presley-lpc/p/9689729.html
Copyright © 2011-2022 走看看