首页 > 编程语言 > 详细

python面向对象2 --各种方法

时间:2021-07-07 12:44:23      阅读:13      评论:0      收藏:0      [点我收藏+]
1、面向对象的各种方法:
属性方法:@property这个装饰器;看起开来像变量的一个方法
类变量:公共的,随着类一起定义
类方法:@classmethod 这个修饰器,函数里传(cls);不用实例化也能调用,可以节省内存
静态方法:@staticmethod ;(该函数不传入self或者cls),所以不能调用类属性和实例属性,但是别的方法可以调用他
__getattr__: 魔术方法
import time
class Car:
    country = "China" #类变量

    @staticmethod  #静态方法
    def say():
        print("哈哈哈")

    @classmethod #类方法
    def help(cls):
        print("请拨打客服热线4090xxxxx")

    def __init__(self,name):
        self.__name = name #实例变量
        self.crete_time = int(time.time()) - 60 * 60 * 24 * 365 * 5
    #实例方法
    def run(self):
        print("%s,run" % self.__name)

    @property #属性方法
    def age(self):
        car_age = ( int(time.time()) - self.crete_time ) / (60 * 60 * 24 * 365)
        return car_age
    def __getattr__(self, item): # 魔术方法
        print("item",item)


qq = Car("奇瑞qq")
print(qq.age)
print(qq.hhh)
# Car.help()

2、经典类,新式类:

class A: #经典类
     pass
class A():#新式类
     pass

 

python面向对象2 --各种方法

原文:https://www.cnblogs.com/kangfei/p/14979984.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!