属性 类方法 静态方法 反射

 

属性:
例一:BMI指数(bmi是计算而来的,
但很明显它听起来像是一个属性而非方法,如果我们将其做成一个属性,更便于理解)

成人的BMI数值:
过轻:低于18.5
正常:18.5-23.9
过重:24-27
肥胖:28-32
非常肥胖, 高于32
  体质指数(BMI)=体重(kg)÷身高^2(m)
  EX:70kg÷(1.75×1.75)=22.86

 

1,初识属性:
class A:
    def __init__(self, name, weight, height):
        self.name = name
        self.__weight = weight
        self.__height = height

    @property  # 属性
    def bmi(self):
        return self.__weight / self.__height ** 2



ly = A('女司机', 54, 1.6)
print(ly.bmi)
View Code
属性:将方法 伪装 成属性,虽然在代码层面上没有任何高深之处,
但是让其看起来更合理.
2,属性改,和删除.
class Mes:
    def __init__(self, name, age,password):
        self.__name = name
        self.__age = age
        self.__password = password

    @property
    def password(self):
        '''对密码加密'''
        self.__password = hash(self.__password + 'sb')
        return self.__password

    @password.setter
    def password(self,new_password):
        if type(new_password) is str:
            self.__password = new_password
        else:
            print('请输入字符串类型')
    @password.deleter
    def password(self):
        print(6666)
p1 = Mes('张三', 18)
p1.name = '张三三'
print(p1.name)
print(p1.name)
p1 = Mes('张三', 18,'hao123')
print(p1.password)
之前对属性的更改
p1.name = 'alex'
p1.password = '123456'
print(p1.password)
del p1.password
print(p1.password)
View Code
第一步,对属性进行改操作,自动执行 被这个@password.setter装饰器装饰的方法
第二步,将新值传给这个被@password.setter装饰器装饰的方法里面,当做参数.
property ***
@password.setter  *
@password.deleter
class Mes:
    def __init__(self, name, age,password):
        self.name = name
        self.__age = age
        self.__password = password

    @property
    def password(self):
        return self.__password

    @password.setter
    def password(self,new_password):
        self.__password = new_password

    @password.deleter
    def password(self):
        del self.__password

p1 = Mes('张三', 18, 'hao123')
p1.name = 'alex'
print(p1.name)
print(p1.password)
p1.password = '123456'  # 这只是行代码,没有真正的改.(触发了那个函数)
print(p1.password)
del p1.password
print(p1.password)
View Code
商品类  封装商品名,商品原价, 商品折扣  定义一个方法,计算商品现价.
class Goods:
    def __init__(self,name,original_price,discount):
        self.name = name
        self.__original_price = original_price
        self.__discount = discount

    @property
    def price(self):
        return self.__original_price * self.__discount

    @property
    def original_price(self):
        return self.__original_price

    @original_price.setter
    def original_price(self,new_original_price):
        self.__original_price = new_original_price

apple = Goods('苹果',5,0.95)
print(apple.price)
apple.original_price = 10
print(apple.price)
View Code
类方法,静态方法:
class A:
    __name = 'alex'
    def func(self):
        print(self,'in  func')

    @classmethod   # 类方法
    def func1(cls):
        print(cls, 'in func1')

    def change(self,new_name):
        A.__name = new_name
        return A.__name
    @classmethod
    def change(cls,new_name):
        A.__name = new_name
        return A.__name

a1 = A()
a1.func()
A.func(a1)

类名去调用类方法,自动将类的空间传给类方法中的cls
对象如果调用类方法,自动将类空间传给类中的cls
A.func1()
a1.func1()
什么情况下使用类方法?
直接让类去操作类中的方法,没有必要创建对象在操作的时候,用类方法.
a2 = A()
print(a2.change('wusir'))
print(A.change(111,'wusir'))
print(A.change('wusir'))
View Code
类名去调用类方法,自动将类的空间传给类方法中的cls
对象如果调用类方法,自动将类空间传给类中的cls
什么情况下使用类方法?
直接让类去操作类中的方法,没有必要创建对象在操作的时候,用类方法.
静态方法:
class A:
    __name = 'alex'
    def func(self):
        print(self,'in  func')

    @classmethod   # 类方法
    def func1(cls):
        print(cls, 'in func1')


    @staticmethod  # 静态方法
    def login(username,password):
        print('登录成功...')

A.login('alex', '123')
View Code
静态方法:在类中定义一个静态方法,无需传入你的类空间,对象空间,可以当成普通函数去用.
反射:
非常非常非常非常重要的方法.
通过 字符串 操作一个空间 (对象).
getattr()   用于模块的取文件属性返回某属性
hasattr()   判断检查对象是否拥有某个属性
setattr()   函数置文件属性方法将对象中的属性设置为新的属性
delattr()   删除对象中的属性删除
1,实例化一个对象去研究
class A:
    country = 'China'

    def __init__(self, name, age):
        self.name = name
        self.age = age


a1 = A('alex', 1000)
print(a1.name)
print(getattr(a1,'name1'))  从对象中得到这个属性对应的值
print(hasattr(a1,'age'))   判断此对象中,有没有这个属性
setattr(a1,'sex','')
setattr(a1,'name','wusir')
print(getattr(a1,'name'))
print(getattr(a1,'sex'))  # 对一个对象设置属性
delattr(a1,'name')  # 对一个对象属性删除
print(getattr(a1,'name'))

if hasattr(a1,'name1'):
    getattr(a1,'name1')
else:
    print('没有...')
View Code
2,类中去研究.
class A:
    country = 'China'
    job = 'student'

    def __init__(self, name, age):
        self.name = name
        self.age = age
    def func(self):
        print('in func')
print(getattr(A,'country1',False))
if getattr(A,'country1',False):
content = input('>>>').strip()  # country
print(A.content)  #(A.'country')
# 报错,因为输入的是字符串类型,A.content中content是变量
name = '1 + 2'
name2 = 'name'
print(eval(name2))


print(A.country)
print(A.content)
print(eval('1+ 2'))
正确的:
content = input('>>>').strip()  # 'country'字符串
你拿到的是一个字符串类型,然后你又想对这个类进行操作
if hasattr(A,content):
    print(getattr(A,content))

print(getattr(A,'job1','没有此值'))
print(getattr(A,'func'))
getattr(A,'func')(11)
View Code
3,其他模块去研究.
建立一个模块:
class B:
    name_list = ['张三','旭哥','李四','旭哥']

    @staticmethod
    def add(a,b):return a+b

def login(username,password):
    if username == 'alex' and password == '123':
        return '登录成功'
    else:
        return '登录失败'

导入模块进行操作:
import oldboy
print(oldboy.B.name_list)

bobj = getattr(oldboy,'B')
print(getattr(bobj,'name_list'))

print(getattr(oldboy.B,'name_list'))

print(getattr(oldboy.B,'add')(3,4))
print(getattr(oldboy,'login')('alex','123'))
def func():
    pass
print(func())
View Code
4,本模块(本文件)去研究.
import sys
def login():
    print(55)

def func3():
    print(333)

content = input(">>>")
print(content())  # 这样错的  ,输入的是字符串
print(sys.modules[__name__])
getattr(sys.modules[__name__],'login')()
View Code
装饰器函数

property
classmethod
staticmethod
装饰器
圆形
半径  r
面积  area
周长 perimeter
from math import pi
class Circle:
    def __init__(self,r):
        self.r = r
    @property
    def area(self):
        return self.r**2*pi
    @property
    def perimeter(self):
        return 2*pi*self.r
c = Circle(5)
c.r
print(c.area)  #==>c.area()
c.perimeter  
将一个方法伪装成一个属性
@property:把一个方法伪装成一个属性
@名字.setter 在修改一个属性的时候调用这个方法
@名字.deleter 在del.属性名的时候调用这个方法
@classmethod
类方法
调用者是一个类
有默认参数,cls,表示当前类
在什么时候使用类方法?
只有使用类中的静态属性或者类方法或者静态方法的时候
@staticmethod静态方法
调用者也是一个类
没有默认必须穿的参数
什么时候用静态方法
既不会用到对象的资源也不会用到类的资源的时候
class Person:
    def __init__(self,name):
        self.__name = name
    @property
    def name(self):
        return self.__name
alex = Person('alex')
print(alex.name)

class Person:
    def __init__(self,name):
        self.__name = name
    @property
    def name(self):
        return self.__name
    @name.setter
    def name(self,new):
        self.__name = 'sb'
alex = Person('alex')
print(alex.name)
alex.name = 1234 #能不能改?——不能直接改
print(alex.name)
class Person:
    def __init__(self,name):
        self.__name = name
    @property
    def name(self):
        return self.name
    @name.setter
    def name(self,new):
        if type(new) is str:
            self.__name = new
alex = Person('alex')
print(alex.name)
alex.name = 'sb'
print(alex.name)

class Demo:
    @property
    def wahaha(self):
        print('in wahaha')
        return 'wahaha'
d = Demo()
d.wahaha

class Demo:
    @property
    def wahaha(self):
        print('in wahaha')
        return 'wahaha'
    @wahaha.setter
    def wahaha(self,new):
        print('执行setter方法了',new)
d = Demo
print(d.wahaha)  #可以被查看
d.wahaha = 123  #可以被修改


class Demo:
    def __init__(self,wahaha):
        self.__wahaha = wahaha
    @property
    def wahaha(self):
        print('in wahaha')
        return self.__wahaha
    @wahaha.setter
    def wahaha(self,new):
        self.__wahaha = new
d = Demo
print(d.wahaha)  #可以被查看
d.wahaha = 123  #可以被修改
print(d.wahaha)
View Code
某一种商品打特价:
class Goods:
    def __init__(self,discount,origin_price):
        self.__price = origin_price
        self.__discount = discount
    @property
    def price(self):
        return self.__price*self.__discount
apple = Goods(0.8,10)
print(apple.price)
一个属性可以被查看,可以被修改,
可以被删除吗?
class Goods:
    def __init__(self,discount,origin_price):
        self.__price = origin_price
        self.__discount = discount
    @property
    def price(self):
        return round(self.__price * self.__discount,2)
    @price.setter
    def price(self,new_price):
        self.__price = new_price

apple = Goods(0.8,10)
print(apple.price)
apple.price = 12
print(apple.price)

class A:
    def __init__(self,path):
        self.f = open('path','w')
    def write(self,count):
        self.f.write(count)

class A:
    def __init__(self,path):
        self.f = open(path,'w')
    def write(self,content):
        self.f.write(content)
    def close(self):
        self.f.close()
obj = A('wahaha')
obj.write('wahahayawahaha')
obj.close()
del obj.f    #f变量删除,文件没有关闭
#open()






class A:pass
a = A()
a.name = 'egon'
print(a.__dict__)
del a.name
print(a.__dict__)

class A:
    def __init__(self,path):
        self.__f = open(path,'w')
    @property
    def f(self):return self.__f

    @f.deleter
    def f(self):      # 所有的借用操作系统的资源,在删除一个变量之前都必须先归还资源
        self.close()
        del self.__f

    def write(self,content):
        self.__f.write(content)

    def close(self):
        self.__f.close()

obj = A('wahaha')
obj.write('wahahayawahaha')
obj.close()

del obj.f   # f变量删除,文件没有关
print(obj.f)
某一商品打特价
method 方法——函数
property 伪装成属性的方法 —— 特性
classmethod 类方法
staticmethod静态方法
class Goods:
    __discount = 0.8
    def __init__(self,origin_price):
        self.__price = origin_price
    @property
    def price(self):
        return round(self.__price*Goods.__discount,2)
    @price.setter
    def price(self,new_price):
        self.__price = new_price
        def change_discount(self,new_discount):
            Goods.__discount = new_discount
apple = Goods
apple.change_discount(1)
print(apple.price)
商品打特价
类方法:
class Goods:
    __discount = 0.8
    def __init__(self,origin_price):
        self.__price = origin_price
    @property
    def price(self):
        return round(self.__price * Goods.__discount,2)
    @price.setter
    def price(self,new_price):
        self.__price = new_price
    @classmethod
    def change_discount(cls,new_discount):
        # print(cls,Goods)
        #Goods.__discount = new_discount
        cls.__discount = new_discount

# apple = Goods(10)
# apple.change_discount(1)
Goods.change_discount(0.7)
apple = Goods(10)
print(apple.price)
View Code
静态方法:
class Student:
    def __init__(self,name,sex):
        self.name = name
        self.sex = sex

    @staticmethod   # 相当于函数
    def login():
        name = input('>>')
        if name == 'alex':print('登录成功')
# 学生的登陆行为
Student.login()
View Code
method        方法 —— 函数               由实例化对象去调用
property      伪装成属性的方法 —— 特性     由实例化对象去调用
classmethod   类方法                     由类调用,只使用类中的静态变量
staticmethod  静态方法                   由类调用,一个方法既不会用到对象的属性,也不会用到类的属性

 

posted on 2018-07-03 13:56  liangliang123456  阅读(552)  评论(0编辑  收藏  举报

导航