Python学习笔记二(面向对象-类-方法-属性)



函数的定义
class
Python中的类没有什么public、private、protect

构造函数、析构函数
__init__(self)
__del__(self)

类的静态变量
class Student
  name="abc"
这东西其实就是相当于C#中的静态变量,但这里要注意是,初始化类的静态变量是这样的(DiveIntoPython中的例子)
class counter:
    count = 0                    
    def __init__(self):
      self.__class__.count += 1

实例的成员变量
class Student
  def __init__(self)
      self.name = "abc"


属性定义(类从object继承,但好像不是必须的,因为下面的代码也可以正常使用)
class Student:
    def __init__(self):
        self.__name="abc"
    def GetName(self):
        return self.__name
    def SetName(self,value):
        self.__name = value
    def DelName(self):
        del self.__name
    Name = property(GetName,SetName,DelName,'Student name')
说实话,当我写完这段代码的时候,我就不想使用属性了。这样定义起来也太不方便了,还要从object中继承。而且现在C#中,可以很简单的通过get、set来实现属性了。目前没有找到好的理由使用属性

只读属性(类必须从object继承,否则就不是只读的)
class Parrot(object):
    def __init__(self):
        self._voltage = 100000
    @property
    def voltage(self):
        """Get the current voltage."""
        return self._voltage

私有变量
class Student:
    def __init__(self):
        self.__name="abc"
很简单就是通过__ 两个下划线开头,但不是结尾的。就是私有了

私有方法
class Student:
    def __Getage(self):
        pass
和私有的变量一样,你可以尝试一下直接调用,编译器会有相应的提示

强制访问私有方法、变量
"私有"事实上这只是一种规则,我们依然可以用特殊的语法来访问私有成员。
上面的方法,我们就可以通过_类名来访问
aobj = Student()
aobj._Student__name
aobj._Student__Getage()

静态方法
class Class1: 
    @staticmethod 
    def test(): 
      print "In Static method..." 

方法重载
python是不支持方法重载,但是你代码了可以写。Python会使用位置在最后的一个。我觉得这可能以Python存储这些信息通过__dict__ 有关,它就是一个Dict。key是不能相同的。所以也就没办法出现两个GoGo 方法调用

class Student:
    def GoGo(self,name):
        print name
    def GoGo(self):
        print "default"

调用的时候你只能使用 obj.GoGo()这个方法。

一些特殊方法

__init__(self)  构造函数
__del__ (self)  析构函数
__repr__( self)   repr()
__str__( self)    print语句 或 str()

运算符重载
__lt__( self, other)
__le__( self, other)
__eq__( self, other)
__ne__( self, other)
__gt__( self, other)
__ge__( self, other)

这东西太多了。大家还是自己看Python自带帮助吧。

一些特殊属性
当你定义一个类和调用类的实例时可以获得的一些默认属性
class Student:
    '''this test class'''
    name = 'ss'
    def __init__(self):
        self.name='bb'
    def Run(self):
        '''people Run'''
    @staticmethod 
    def RunStatic(): 
        print "In Static method..."
print Student.__dict__ #类的成员信息
print Student.__doc__  #类的说明
print Student.__name__ #类的名称
print Student.__module__ #类所在的模块
print Student.__bases__ #类的继承信息
obj = Student()

print dir(obj)
print obj.__dict__ #实例的成员变量信息(不太理解Python的这个模型,为什么Run这个函数确不再dict中)
print obj.__doc__  #实例的说明
print obj.__module__ #实例所在的模块
print obj.__class__ #实例所在的类名

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值