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 '''
  • 相关阅读:
    hdu 5366 简单递推
    hdu 5365 判断正方形
    hdu 3635 并查集
    hdu 4497 数论
    hdu5419 Victor and Toys
    hdu5426 Rikka with Game
    poj2074 Line of Sight
    hdu5425 Rikka with Tree II
    hdu5424 Rikka with Graph II
    poj1009 Edge Detection
  • 原文地址:https://www.cnblogs.com/Presley-lpc/p/9689729.html
Copyright © 2011-2022 走看看