Python之面向对象方法

  property的用法:

    property属于类的封装的范畴

    property是一种特殊的属性,访问它时会执行一段功能(函数),然后返回值。

    用property的方法,就可以实现用property作为装饰器,来直接用被装饰的函数里的数据。

    而不用再繁琐的去用 "__" 的方法去调用。

import math
class Circle:
def __init__(self,radius): #圆的半径radius
self.radius=radius @property #area=property(area)
def area(self):
return math.pi * self.radius**2 #计算面积 @property
def perimeter(self):
return 2*math.pi*self.radius #计算周长 c=Circle(7)
print(c.radius)
c.radius=10 # print(c.area())
# print(c.perimeter())
print(c.area)
print(c.perimeter)
class People:
def __init__(self,name,age,height,weight):
self.name=name
self.age=age
self.height=height
self.weight=weight
@property
def bodyindex(self):
return self.weight/(self.height**2) # p1=People('cobila',38,1.65,74)
# print(p1.bodyindex)
# p1.weight=200
# print(p1.bodyindex)
#被property装饰的属性会优先于对象的属性被使用

#而被propery装饰的属性,如sex,分成三种:
# 1.property
# 2.sex.setter
# 3.sex.deleter #
# class People:
# def __init__(self,name,SEX):
# self.name=name
# # self.__sex=SEX
# self.sex=SEX #self.sex='male' p1.sex='male'
# @property
# def sex(self):
# return self.__sex #p1.__sex
#
# @sex.setter
# def sex(self,value):
# # print(self,value)
# if not isinstance(value,str):
# raise TypeError('性别必须是字符串类型')
# self.__sex=value #p1.__sex='male'
# @sex.deleter
# def sex(self):
# del self.__sex #del p1.__sex # p1=People('cobila','male')
# print(p1.tell_name())
#
# print(p1.sex)
# p1.sex='123' # p1.sex='female'
# print(p1.sex) # p1.sex=123123123123123123123123123213 # p1=People('cobila',123123123123123)
# p1=People('cobila','male')
# print(p1.sex)
# del p1.sex #del self.sex
# print(p1.sex) class People:
def __init__(self,name,SEX):
self.name=name
# self.__sex=SEX
self.sex=SEX#p1.sex='male' @property
def sex(self):
print('------proerty---------------------->')
return self.__sex @sex.setter
def sex(self,value):
print('===================》')
# print(self,value)
# if not isinstance(value,str):
# raise TypeError('性别必须是字符串类型')
self.__sex=value #p1.ABCDEFG='male'
@sex.deleter
def sex(self):
print('delete 操作')
del self.__sex p1=People('George','male')
# print(p1.__dict__)
# print(p1.sex)
# del p1.sex
# print(p1.sex) # print(p1.ABCDEFG)
# p1.ABCDEFG=123123
# print(p1.ABCDEFG) # p1.sex
# print(p1.__dict__) # p1.sex # p1.sex='mall' # del p1.sex

  staticmethod的用法:

     应用场景:

      

# class Foo:
# def spam(self):
# print('----->',self)
#
#
# # Foo.spam(123123)
#
# f1=Foo()
# f1.spam() # class Foo:
# @staticmethod
# def spam(x,y,z):
# print(x,y,z)
#
#
# # Foo.spam(1,2,3)
# f2=Foo()
# f2.spam(1,2,3) import time
class Date:
def __init__(self,year,month,day):
self.year=year
self.month=month
self.day=day
#
# def test():
# print('from test')
#
@staticmethod
def now(): #用Date.now()的形式去产生实例,该实例用的是当前时间
t=time.localtime() #获取结构化的时间格式
obj=Date(t.tm_year,t.tm_mon,t.tm_mday) #新建实例并且返回
return obj @staticmethod
def tomorrow():#用Date.tomorrow()的形式去产生实例,该实例用的是明天的时间
t=time.localtime(time.time()+86400)
return Date(t.tm_year,t.tm_mon,t.tm_mday)
# d1=Date(2017,1,13)
# # Date.test()
# print(d1.test)
# d1.test() # d1=Date(2017,1,13)
# d2=Date(2017,1,14)
# date_now=Date.now()
# print(date_now)
# print(date_now.year)
# print(date_now.month)
# print(date_now.day) # d1=Date.now()
# print(d1.year,d1.month,d1.day)
#
# d2=Date.tomorrow()
# print(d2.day) #但凡是定义在类的内部,并且没有被任何装饰器修饰过的方法,都是绑定方法:有自动传值功能
d1=Date(1212,22,22)
print(d1.now)
print(Date.now)
# d1.now() #now(d1) #但凡是定义在类的内部,并且被staticmethod装饰器修饰过的方法,都是解除绑定的方法,实际上就函数:就没有自动传值功能了
d_n1=Date.now()
d_n2=d1.now()
print(d_n1.year,d_n1.month,d_n1.day)
print(d_n2.year,d_n2.month,d_n2.day)

  

  classmethod的用法:

#把一个方法绑定给类:类.绑定到类的方法(),会把类本身当做第一个参数自动传给绑定到类的方法
#拿掉一个类的内存地址后,就可以实例化或者引用类的属性了
class Foo:
def bar(self):
pass
@classmethod #把一个方法绑定给类:类.绑定到类的方法(),会把类本身当做第一个参数自动传给绑定到类的方法
def test(cls,x):
print(cls,x) #拿掉一个类的内存地址后,就可以实例化或者引用类的属性了 # print(Foo.bar)
# print(Foo.test) Foo.test(123123) f=Foo()
print(f.bar)
print(f.test)
print(Foo.test)
f.test(1111)
import time
class Date:
def __init__(self,year,month,day):
self.year=year
self.month=month
self.day=day
#
# def test():
# print('from test')
#
@classmethod
def now(cls): #用Date.now()的形式去产生实例,该实例用的是当前时间
print(cls)
t=time.localtime() #获取结构化的时间格式
obj=cls(t.tm_year,t.tm_mon,t.tm_mday) #新建实例并且返回
return obj @classmethod
def tomorrow(cls):#用Date.tomorrow()的形式去产生实例,该实例用的是明天的时间
t=time.localtime(time.time()+86400)
return cls(t.tm_year,t.tm_mon,t.tm_mday) class EuroDate(Date):
def __str__(self):
return '年:%s,月:%s,日:%s' %(self.year,self.month,self.day) # e1=EuroDate.now()
# print(e1) e1=EuroDate(1,1,1)
print(e1)

  __str__ 的用法:

#__str__定义在类内部,必须返回一个字符串类型,
#什么时候会出发它的执行呢?打印由这个类产生的对象时,会触发执行
   
#__str__定义在类内部,必须返回一个字符串类型,
#什么时候会出发它的执行呢?打印由这个类产生的对象时,会触发执行 class People:
def __init__(self,name,age):
self.name=name
self.age=age
def __str__(self):
return '<name:%s,age:%s>' %(self.name,self.age) p1=People('George',18)
print(p1)
str(p1) #----->p1.__str__()

  链接:详细

Python之面向对象方法的更多相关文章

  1. python基础——面向对象编程

    python基础——面向对象编程 面向对象编程——Object Oriented Programming,简称OOP,是一种程序设计思想.OOP把对象作为程序的基本单元,一个对象包含了数据和操作数据的 ...

  2. python类及其方法

    python类及其方法 一.介绍 在 Python 中,面向对象编程主要有两个主题,就是类和类实例类与实例:类与实例相互关联着:类是对象的定义,而实例是"真正的实物",它存放了类中 ...

  3. Python的面向对象3

    接下来,我们接着讲Python的面向对象,在上一次的博客中,我们详细介绍了类与对象的属性,今天,我们来详细介绍一下面向对象中的方法! 1.定义实例方法 一个实例的私有属性就是以__开头的属性,无法被外 ...

  4. Python的面向对象2

    我们接着讲解Python的面向对象 1.初始化实例属性 在现实生活中,一种类型的实例会具有相同的某些属性,把这些实例划分为一个类型,则这些实例必然有相似的部分.但是,在创建实例之后,我们一个一个的为实 ...

  5. Python的面向对象1

    今天,我们来介绍Python的面向对象编程,其实面向对象并不陌生,在C++  ,Java  ,PHP中也有大量使用! 好了,我们来步入正题! 那什么是面向对象编程呢? 1. 面向对象编程是一种程序设计 ...

  6. Python进阶---面向对象的程序设计思想

    Python的面向对象 一.面向过程与面向对象的对比 面向过程的程序设计的核心是过程(流水线式思维),过程即解决问题的步骤,面向过程的设计就好比精心设计好一条流水线,考虑周全什么时候处理什么东西. 优 ...

  7. Python之面向对象一

    引子 小游戏:人狗大战 角色:人和狗 角色属性:姓名,血量,战斗力和性别(种类) 技能:打/咬 用函数实现人打狗和狗咬人的情形 def Dog(name,blood,aggr,kind): dog = ...

  8. python基础——面向对象进阶下

    python基础--面向对象进阶下 1 __setitem__,__getitem,__delitem__ 把对象操作属性模拟成字典的格式 想对比__getattr__(), __setattr__( ...

  9. python基础——面向对象进阶

    python基础--面向对象进阶 1.isinstance(obj,cls)和issubclass(sub,super) isinstance(obj,cls)检查是否obj是否是类 cls 的对象 ...

随机推荐

  1. [BUG]Dreamweaver6做网页的一个图片文字不清晰的问题

    自己用Dreamweaver6做一个网页,使用PS做图片,为了节约下载流量,我把图片裁剪为GIF格式,通过系统自带的图片浏览器和美图看看,图片上的文字都是清晰的. 我把图片加载进入DW中后,在DW界面 ...

  2. 浏览器 cookie session

    浏览器的cookie被禁用的话,则服务端的session不起作用 session是基于cookie实现的, 还是办理会员卡的问题, cookie客户端支持,即客户手上的会员卡记录了所有信息, sess ...

  3. 利用正则将xml数据解析为数组

    function xml_to_array( $xml ) { $reg = '/<(\w+)[^>]*>([\x00-\xFF]*)<\/\1>/'; if(preg_ ...

  4. solr之~模糊查询【转】

    solr之~模糊查询 有的时候,我们一开始不可能准确地知道搜索的关键字在 Solr 中查询出的结果是什么,因此,Solr 还提供了几种类型的模糊查询.模糊匹配会在索引中对关键字进行非精确匹配.例如,有 ...

  5. 获取select里面option所有的值

    1.HTML结构 <select id="test"> <option value="option-1">option-1</op ...

  6. SPFarm.local返回值为null

    创建了一个控制台应用程序,想输出SP2010服务器场下所有对象模型信息,结果:SPFarm.local返回值为null. 经查询解决方法: 1 .net framework版本要使用3.5: 2 目标 ...

  7. poj1930 Dead Fraction

    思路: 循环小数化分数,枚举所有可能的循环节,取分母最小的那个. 实现: #include <iostream> #include <cstdio> #include < ...

  8. idea 调试工具的使用

    原文:https://blog.csdn.net/hao_hl1314/article/details/53120918 Intellij IDEA Debug调试区工具的使用方法 快捷键F9     ...

  9. window下phpstudy开启redis扩展

    注:一定要注意自己PHP的版本结构是64还是32位的!其次查看PHP Extension Build是NTS or TS! 1.使用phpinfo()函数查看PHP的版本信息,这会决定扩展文件版本(特 ...

  10. [转]1小时内打造你自己的PHP MVC框架

    简介 MVC框架在现在的开发中相当流行,不论你使用的是JAVA,C#,PHP或者IOS,你肯定都会选择一款框架.虽然不能保证100%的开发语言都会使用框架,但是在PHP社区当中拥有*多数量的MVC框架 ...