• Python类(一)-实例化一个类


    #-*- coding:utf-8 -*-
    __author__ = "MuT6 Sch01aR"
    
    class Person():
        n = 123   #类变量
        def __init__(self,name,money,age=33):  #构造函数
        #给实例化的类传参数
            self.name = name    #实例变量
            self.money = money
            self.__age = age   #私有属性,在外部不能调用查看,可以在内部定义函数来查看
    
        def Age(self):
            print("%s is %s Yeas Old." %(self.name,self.__age))
    
        def talk(self):   #类的方法、功能(动态属性)
            print("%s is talking to the shop." % self.name)
    
        def buy(self, thing):
            print("%s has %s$ and buy a %s" % (self.name,self.money, thing))
    
        def __walk(self):  #私有方法
            print("%s is walking" %self.name)
    
        def __del__(self):  #析构函数,全部实例释放、销毁时会自动执行,通常用于收尾工作
           print("%s is die." %self.name)
    
    p1 = Person("Jack",100)  #实例化一个对象
    p1.talk()     #调用Person里的talk方法
    p1.buy("meat")  #给Person里的buy传参
    
    p1._Person__walk()  #访问私有方法
    
    p1.walk = True  #给p1新增一个属性
    
    p1.n = "test"
    print(p1.n)
    
    #del p1  #如果不想等实例释放时才删除,可以先删除实例
    
    print(p1.Age())  #查看私有属性
    
    #del p1.talk   #删除类的talk方法
    #p1.talk()  #会报错,因为talk方法被删除了
    

     def __init__(self) 为构造函数,给实例化的类传参数,self为实例化的对象赋予的变量,相当于例子中的p1

    运行结果

  • 相关阅读:
    log4j2RCE复现
    Kernel panic: VFS: Unable to mount root fs on 08:08 解决方法
    关于QEMU/KVM中无法开启eth0网卡解决方法
    20212022年寒假学习进度04
    20212022年寒假学习进度05
    每日学习
    课程总结和加分项
    每日学习
    20212022年寒假学习进度03
    20212022年寒假学习进度01
  • 原文地址:https://www.cnblogs.com/sch01ar/p/7769046.html
Copyright © 2020-2023  润新知