猫史档案馆


讲解类中的特殊方法:带教程!

用户:TimeLinkForeverTimeLinkForever查看:0 回复:0 评论:0 创建时间:2020-01-05T15:11:40


emotion_编程猫_嗨起来第一次发帖

注意,此贴仅可使用python 2.x!!!!!!!!

有些类方法的笔记由于是直接从网上粘下来的所以没有!

1.__str__的用法

示例代码:

class hahaha(object):

    def __init__(self,name,age):

        self.name=name

        self.age=age

yayaya=hahaha("plarser",92)

print yayaya

输出竟然是:

E:\python code>C:/Python27/python.exe "e:/python code/test/code_example.py"

<__main__.hahaha object at 0x00000000036F3358>

这是为什么呢?

其实这段指的是由hahaha创建的实例的在内存中的位置。

如果要打印出:

Hahaha,I am plarser,I am 92 years old.

就需要用到__str__方法了。

将原来的示例代码修改一下:

class hahaha(object):

    def __init__(self,name,age):

        self.name=name

        self.age=age

  def __str__(self):

return "Hahaha,I am",self.name,",I am",self.age,"years old."

yayaya=hahaha("plarser",92)

print yayaya

然鹅……

E:\python code>C:/Python27/python.exe "e:/python code/test/code_example.py"

Traceback (most recent call last):

  File "e:/python code/test/code_example.py", line 8, in <module>

    print yayaya

TypeError: __str__ returned non-string (type tuple)

⊙△⊙?⊙△⊙?⊙△⊙?⊙△⊙?⊙△⊙?⊙△⊙?⊙△⊙?⊙△⊙?⊙△⊙?⊙△⊙?⊙△⊙?⊙△⊙?⊙△⊙?⊙△⊙?

 

 

╭︿︿︿╮

{/ -  - /}

( (..) )

  ︶︶︶

为啥呢?

错误提示告诉我们

我们给出的是tuple元组,所以我们要用%的那种。

class hahaha(object):

    def __init__(self,name,age):

        self.name=name

        self.age=age

    def __str__(self):

        return "Hahaha,I am %s,I am %d years old."%(self.name,self.age)

yayaya=hahaha("plarser",92)

print yayaya

E:\python code>C:/Python27/python.exe "e:/python code/test/code_example.py"

Hahaha,I am plarser,I am 92 years old.

介不就对了嘛。

总结:

哈哈。

__str__是用来控制类打印时的输出的

不可输出tuple类型(逗号法)

而要使用%的那种。

2.__repr__的使用

跟__str__一样,str给用户,repr给开发者。

一般会__repr__=__str__

不过如果你真的有点那啥要测试之类的

如下面例子中的testcode……..

class hahaha(object):

    def __init__(self,name,age):

        self.name=name

        self.age=age

        self.testcode=len(self.name)+age

        

    def __str__(self):

        return "Hahaha,I am %s,I am %d years old."%(self.name,self.age)

    def __repr__(self):

        return "test:%s,%d,%d"%(self.name,self.age,self.testcode)

yayaya=hahaha("plarser",92)

print yayaya

print repr(yayaya)

输出:

E:\python code>C:/Python27/python.exe "e:/python code/test/code_example.py"

Hahaha,I am plarser,I am 92 years old.

test:plarser,92,99

这里再附上小贴士:

Print __repr__,__str__会返回内存位置

Print repr(self) 才行。

重要:

Python会首先选择已经被定义的str或repr,在str没有被定义时,Python会选择在调用str时去调用repr的,如果定义了,则优先选择str了!

1.len与__len__

Len?__len__?有嘛子区别呀?

Len()是一个函数,对文本及列表有作用

如:len("hello")=5,len([1,2,3,4,5])=5

But __len__是一个类方法!

2.__len__

话说当你创建了一个类……

上代码!

class testclassequal(object):

    def __init__(self,num,d,start):

        list=[]

        j=start

        for i in range(num):

            list.append(j)

            j+=d

        self.rop=list

    def __str__(self):

        return "%s"% self.rop

    def __len__(self):

        return len(self.rop)

a=testclassequal(100,3,0)

print a

print len(a)

它高雅地返回:

E:\python code>C:/Python27/python.exe "e:/python code/test/listclassexample.py"

[0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72, 75, 78, 81, 84, 87, 90, 93, 96, 99, 102, 105, 108, 111, 114, 117, 120, 123, 126, 129, 132, 135, 138, 141, 144, 147, 150, 153, 156, 159, 162, 165, 168, 171, 174, 177, 180, 183, 186, 189, 192, 195, 198, 201, 204, 207, 210, 213, 216, 219, 222, 225, 228,

231, 234, 237, 240, 243, 246, 249, 252, 255, 258, 261, 2喵, 267, 270, 273, 276, 279, 282, 285, 288, 291, 294, 297] 

100

 

就是这样。

总结:

1.len()和__len__有区别

2.__len__按需自取,可适用于列表类

int float

用p/q来表达一个rational有理数,但这次——

我们要int,float一个类!

  跟__str__类似,__int__和__float__也各自对应的int()和float().

我们来看刚裁下来的rational类:

他的表达式只有__str__方法里面有

我们要给它设置int和float方法:

Int:

用p整除掉q

Float:

用float(p)➗q

然后就可以填入表达式了。

惊不惊喜????意不意外????

就这么简单。

上代码:

Before:

class Rational:

    def __init__(self,p,q):

        self.p=p

        self.q=q

    def __str__(self):

        return "Now print the Rational number:%d/%d"%(self.p,self.q)

    def __int__(self):

        #??????how to code???

    def __float__(self):

        #??????how to code???

a=Rational(100,51)

print a

#print int(a)

#print float(a)

After:

class Rational:

    def __init__(self,p,q):

        self.p=p

        self.q=q

    def __str__(self):

        return "Now print the Rational number:%d/%d"%(self.p,self.q)

    def __int__(self):

        return self.p//self.q

    def __float__(self):

        return float(self.p)/self.q

a=Rational(100,51)

print a

print int(a)

print float(a)

Output:

E:\python code>C:/Python27/python.exe "e:/python code/test/test.py"

Now print the Rational number:100/51

1

1.96078431373

有时你可以弄些好玩的——

class Rational:

    def __init__(self,p,q):

        self.p=p

        self.q=q

    def __str__(self):

        return "Now print the Rational number:%d/%d"%(self.p,self.q)

    def __int__(self):

        return 14524

    def __float__(self):

        return 14524.54188

a=Rational(100,51)

print a

print int(a)

print float(a)

slot

__slot__是一个好玩的方法!!!

当你不想让别人给你的类添点什么东西时它就起效了

__slot__是用来添加锁定类属性列表的,当启用该列表时,添加新的属性就会报错!!!!!!!!

代码上!

class Person(object):

 

    __slots__ = ('name', 'gender')

 

    def __init__(self, name, gender):

        self.name = name

        self.gender = gender

 

class Student(Person):

 

    __slots__ = ("name","gender","score")

 

    def __init__(self,name,gender,score):

        super(Student,self).__init__(name,gender)

        self.score=score

 

s = Student('Bob', 'male', 59)

s.name = 'Tim'

s.score = 99

print s.score

 

 

 

__slot__贼厉害!文中加蓝的部分就使用了slot锁定列表!试一试加上一个新建属性!

class Person(object):

    __slots__ = ('name', 'gender')

    def __init__(self, name, gender):

        self.name = name

        self.gender = gender

class Student(Person):

    __slots__ = ("name","gender","score")

    def __init__(self,name,gender,score):

        super(Student,self).__init__(name,gender)

        self.score=score

s = Student('Bob', 'male', 59)

s.grade="A+"

 

看看发生了什么呢?

E:\python code>C:/Python27/python.exe "e:/python code/test/test.py"

Traceback (most recent call last):

  File "e:/python code/test/test.py", line 18, in <module>

    s.grade="A+"

AttributeError: 'Student' object has no attribute 'grade'

 

看到没有?计算机明确指出没有grade这个attribute,这次就能阻挡新的变量创建了!

千万注意__slot__:

这是一个(元组),且其中的属性全部用文本串表达。

call

Python__call__:可调用对象

可调用对象是一个可以被调用的对象。

所有函数都是可调用对象。

实例可调用对象的用处:

p=isinstance

print p(1324.124,int)

返回了false

但是当我们想要把一个类当个function的话

可以使用__call__

代码来了!

 

它发回了一个菲薄那奇欧数列(斐波那契数列)

注意:

如果要打印的话,调用时不要print func(),直接return就好

-----------------------END---------------------------

 

 

 

 


回复

上一页1 页 / 共 0下一页