Python之面向对象:属性

一、属性定义
1、类属性
类属性定义在类中且在函数体之外;类属性通常不作为实例属性使用;类变量紧接在类名后面定义
类属性的引用:类名.count eg:Employee.count
实例中可以引用类的属性:
a、通过类名引用
b、通过实例名:读取的操作,写的操作(操作的属性是实例的属性,不是类的属性,对类的属性没有影响)
 
2、实例属性
定义在方法中的变量,只作用于当前实例的类;实例变量在__init__()函数里定义
如果所添加的属性名与类中类属性名相同的时,类属性在这个实例对象中就会被屏蔽掉,也就是说实例引用时,同名的实例属性会屏蔽同名的类属性,就类似于全局变量与局部变量的关系。
 
3、局部变量
在类的实例方法中定义的变量,叫局部变量,其作用域仅限于其所在的函数内部,执行到该函数,局部变量生成,函数退出后,局部变量被消亡。
 
4、@porperty 属性装饰器
使用:
@property
def score(self):
return self.__score
s1=Student('a',18,90)
print s1.score 直接把方法当属性使用
 
@property.setter @score.setter 修饰器 修改
def score(self,score):
pass
 
s1.score=98 修饰器
@property.deleter @score.deleter 删除
eg:
#encoding=utf-8
class Goods(object):
def __init__(self,price):
self.__price=price
@property
def price(self):
print '@porperty'
return self.__price
@price.setter
def price(self,price1):
self.__price=price1
print '@price setter'
@price.deleter
def price(self):
del self.__price
print '@price.deleter'
 
obj=Goods(100)
print obj.price
obj.price=123
del obj.price
 
5、类的私有属性
两个下划线开头属性,声明该属性为私有属性,不能在类的外部被使用或直接访问,只能在类内部访问。在类内部的方法中使用时的语法:self.__private_attrs。 eg:self.__name
eg:
class Person(object):
__secretCount = 0 #私有属性
def __init__(self, name):
self.name = name #实例属性
self.__inName = 'ads' #私有属性
def visit_private_attribute( self ):
self.__secretCount += 1
print "__secretCount: ", self.__secretCount
print u"__inName:", self.__inName
p = Person("prel")
p.visit_private_attribute() 通过方法获取类的私有属性
print u"在类外直接通过实例访问私有属性"
print p.__inName 在类外直接调用,会报错
 
python的语法并不是那么严格的能够保证私有变量不被随意改动,以下方式可以访问私有属性:
object._className__attrName eg:p._Person__inName
 
二、属性相关
1、修改类属性
修改类属性的值,有三种方法,分别为:
(1)通过类方法修改
(2)通过实例方法修改
(3)直接通过类对象修改
#coding=utf-8
class employee(object) :
city = 'BJ' #类属性
def __init__(self, name) :
self.name = name #实例变量
#定义类方法
@classmethod
def getCity(cls) :
return cls.city
#定义类方法
@classmethod
def setCity(cls, city) :
cls.city = city
#实例方法
def set_City(self, city) :
employee.city = city
 
调用:
emp = employee('joy') #创建类的实例
print emp.getCity() #通过实例对象引用类方法
print employee.getCity()#通过类对象引用类方法
emp.setCity('TJ')#实例对象调用类方法改变类属性的值
print emp.getCity()
print employee.getCity()
employee.setCity('CD')#类对象调用类方法改变类属性的值
print emp.getCity()
print employee.getCity()
emp.set_City('SH')#调用实例方法修改类属性的值
print emp.getCity()
print employee.getCity()
employee.city = 20 #直接修改类属性的值
print emp.getCity()
print employee.getCity()
 
2、作用域
print locals() 返回所有的局部变量
print globals() 返回所有的全局变量
在python的作用域规则里面,创建变量时一定会在当前作用域里创建同样的变量,但访问或修改变量时,会在当前作用域中查找该变量,如果没找到匹配的变量,就会依次向上在闭合作用域中进行查找,所以在函数中直接访问全局变量也是可以的
posted @ 2017-06-21 12:43  emily-qin  Views(650)  Comments(0Edit  收藏  举报