zoukankan      html  css  js  c++  java
  • Day18

    class Person:
        role = 'person'   # 静态属性
        def __init__(self,name,sex,hp,ad):
            self.name = name     # 对象属性 属性
            self.sex = sex
            self.hp = hp
            self.ad = ad
        def attack(self):
            self.hobby = 'girl'
            print('%s发起了一次攻击'%self.name)
    
    alex = Person('a_sb','不详',1,5)
    alex.attack()   # Person.attack(alex)

    1、命名空间和作用域

    alex.name  #alex指向我自己的内存空间,在自己的内存空间里面找到name

    alex.attack  #alex先找自己的内存空间 再找到类对象指针 再根据类对象指针找到类 再通过类找到attack

    对象的内存空间里:只存储对象的属性 而不存储方法和静态属性

    方法和静态属性都存储再类的内存空间中

    为了节省内存,让多个对象去共享类中的资源

    class Person:
        role = 'person'   # 静态属性
        def __init__(self,name,sex,hp,ad):
            self.name = name     # 对象属性 属性
            self.sex = sex
            self.hp = hp
            self.ad = ad
            self.attack = 'hahaha'
        def attack(self):
            print('%s发起了一次攻击'%self.name)
    
    alex = Person('a_sb','不详',1,5)
    boss_jin = Person('金老板','',50,20)
    print(alex.role)
    print(boss_jin.role)
    alex.role = 'dog'
    print(alex.role)
    print(boss_jin.role) #person
    class Person:
        money = 0
        def __init__(self,name):
            self.name = name
        def work(self):
            print(self.name,'工作,赚了1000块钱')
            Person.money += 1000
    
    father = Person('father')
    mother = Person('mother')
    mother.work()
    father.work()
    print(Person.money)    #2000
    class Person:
        money = [1]
        def __init__(self,name):
            self.name = name
        def work(self):
            print(self.name,'工作,赚了1000块钱')
            self.money[0] += 1000
    
    father = Person('father')
    mother = Person('mother')
    mother.work()
    father.work()
    print(Person.money)    #2001
    class Person:
        money = [0]
        def __init__(self,name):
            self.name = name
        def work(self):
            print(self.name,'工作,赚了1000块钱')
            self.money = [Person.money[0] + 1000]
    
    father = Person('father')
    mother = Person('mother')
    mother.work()
    father.work()
    print(Person.money)    #0

    对象属性是独有的,静态属性和方法是共享的

    对象使用名字:先找到自己内存空间中的,再找类的内存空间中的

    类名.静态变量名:对于静态属性的修改,应该使用类名直接修改

  • 相关阅读:
    微信公众号,图片预览功能 有单个图片,
    MUI
    MUI学习01-顶部导航栏
    php验证18位身份证,准到必须输入正确的身份证号,
    微信sdk 图片上传 两种方法 上传一张显示一张 并附带微信图片放大功能和删除功能
    jQuery实现限制input框 textarea文本框输入字符数量的方法
    js jq 手机号实现(344) 附带删除功能 jq 实现银行卡没四个数加一个空格 附带删除功能
    山东省2016acm省赛
    East Central North America Region 2015
    North America Qualifier (2015)
  • 原文地址:https://www.cnblogs.com/a352735549/p/8796257.html
Copyright © 2011-2022 走看看