day7 静太方法 类方法 属性方法 反射 导常

类方法

 1 '''是类对象所拥有的方法,需要用修饰器@classmethod来标识其为类方法,对于类方法
 2 ,第一个参数必须是类对象,一般以cls作为第一个参数(当然可以用其他名称的变量作为其第一个参数,
 3 但是大部分人都习惯以'cls'作为第一个参数的名字,就最好用'cls'了),能够通过实例对象和类对象去访问。'''
 4 
 5 lass People(object):
 6     country = 'china'
 7 
 8     #类方法,用classmethod来进行修饰
 9     @classmethod
10     def getCountry(cls):
11         return cls.country
12 
13 p = People()
14 print p.getCountry()    #可以用过实例对象引用
15 print People.getCountry()    #可以通过类对象引用
16 

17 #类方法还有一个用途就是可以对类属性进行修改: 18 19 class People(object): 20 country = 'china' 21 22 #类方法,用classmethod来进行修饰 23 @classmethod 24 def getCountry(cls): 25 return cls.country 26 27 @classmethod 28 def setCountry(cls,country): 29 cls.country = country 30 31 32 p = People() 33 print p.getCountry() #可以用过实例对象引用 34 print People.getCountry() #可以通过类对象引用 35 36 p.setCountry('japan') 37 38 print p.getCountry() 39 print People.getCountry() 40 41 #结果显示在用类方法对类属性修改之后,通过类对象和实例对象访问都发生了改变

静态方法

需要通过修饰器@staticmethod来进行修饰,静态方法不需要多定义参数

class People(object):
    country = 'china'

    @staticmethod
    #静态方法
    def getCountry():
        return People.country


print People.getCountry()   #可以不用实例化对象来调用静态方法

类方法和静态方法总结:

      从类方法和实例方法以及静态方法的定义形式就可以看出来,类方法的第一个参数是类对象cls,那么通过cls引用的必定是类对象的属性和方法;

而实例方法的第一个参数是实例对象self,那么通过self引用的可能是类属性、也有可能是实例属性(这个需要具体分析),不过在存在相同名称的类属性和实例属性的情况下,

实例属性优先级更高。静态方法中不需要额外定义参数,因此在静态方法中引用类属性的话,必须通过类对象来引用

属性方法:

 

import os
# os.system()
# os.mkdir()

class Dog(object):
    '''这个类是描述狗这个对象的'''

    def __init__(self,name):
        self.name = name
        self.__food = None

    #@staticmethod #实际上跟类没什么关系了
    #@classmethod
    @property #attribute
    def eat(self):
        print("%s is eating %s" %(self.name,self.__food))
    @eat.setter
    def eat(self,food):
        print("set to food:",food)
        self.__food = food
    @eat.deleter
    def eat(self):
        del self.__food
        print("删完了")

    def talk(self):
        print("%s is talking"% self.name)

    def __call__(self, *args, **kwargs):
        print("running call",args,kwargs)

    def __str__(self):
        return "<obj:%s>" %self.name

#print(Dog.__dict__) #打印类里的所有属性,不包括实例属性
d = Dog("ChenRonghua")
print(d)
# print(d.__dict__) #打印所有实例属性,不包括类属性
# d(1,2,3,name=333)

#Dog("ChenRonghua")()

属性方法实例:

__author__ = "Alex Li"

class Flight(object):
    def __init__(self,name):
        self.flight_name = name


    def checking_status(self):
        print("checking flight %s status " % self.flight_name)
        return  0

    @property
    def flight_status(self):
        status = self.checking_status()
        if status == 0 :
            print("flight got canceled...")
        elif status == 1 :
            print("flight is arrived...")
        elif status == 2:
            print("flight has departured already...")
        else:
            print("cannot confirm the flight status...,please check later")
    @flight_status.setter
    def flight_status(self,status):
        print("flight %s has changed status to %s" %(self.flight_name,status))
f = Flight("CA980")
f.flight_status
f.flight_status = 2

反射    这个很重要

语法  

   hasattr(obj,name_str) , 判断一个对象obj里是否有对应的name_str字符串的方法或属性

  getattr(obj,name_str), 根据字符串去获取obj对象里的对应的方法的内存地址
  setattr(obj,'y',z), is equivalent to ``x.y = v''
  delattr(obj,str)

 1 class Dog(object):
 2 
 3     def __init__(self,name):
 4 
 5         self.name = name
 6 
 7     def eat(self):
 8 
 9         print('%s 会吃东西'%self.name)
10 
11 def talk(self):
12     '''输入的值不存在需要添加的方法'''
13     print('%s这只狗会说话'%self.name)
14 
15 d1 = Dog('大黄')
16 
17 inputva = input('>>>')
18 
19 
20 if hasattr(d1,inputva):
21     print(getattr(d1,inputva))
22 else:
23     setattr(d1,inputva,talk)
24     getattr(d1,inputva)(d1)  #返回的是上面set设置的函数的内存地址
25 # delattr(d1,'name') 26 # print(d1.name)

 断言 

1 assert type(age) is int  #断言age是int型 如果是执行下面代码 如果不是中断程序并且抛出异常
2 
3 age / 2
原文地址:https://www.cnblogs.com/qq769080870/p/8538268.html