Python object-oriented advanced programming--Custom classes

Source: Internet
Author: User
Tags stdin

1.1   Custom Classes1.1.1   __str__

>>> class Student (object):

... def __init__ (self, name):

... self.name = name

...

>>> s = Student (' Daidai ')

>>> S.name

' Daidai '

>>> Student (' Daidai '). Name

' Daidai '

>>> Print (Student (' Daidai '))-- It's not good to print

<__main__. Student Object at0x2ac5ebc99128>

>>> class Student (object):

... def __init__ (self, name):

... self.name = name

... def __str__ (self):

... return ' Student object (name:%s) '%self.name

...

>>> Print (Student (' Daidai '))

Student Object (Name:daidai)

>>> s = Student (' Daidai ')

>>> S-- pointing to variables, still not good to see

<__main__. Student Object at0x2ac5ebc99160>

>>> S.name

' Daidai '

will be __str__ also point to __repr__

>>> class Student (object):

... def __init__ (self, name):

... self.name = name

... def __str__ (self):

... return ' Student object (name:%s) '% Self.name

... __repr__ = __str__

...

>>> Print (Student (' Daidai '))

Student Object (Name:daidai)

>>> s = Student (' Daidai ')

>>> S.name

' Daidai '

>>> s

Student Object (Name:daidai)

1.1.2   __iter__

if a class wants to be used for the for ... in loop, like a list or a tuple , you must implement a __iter__ () method that returns an iterative object, and then the Python for Loop constantly calls the iteration object's __next__ () method to get the next value of the loop until it exits the loop when the Stopiteration error is encountered.

Take the Fibonacci sequence for example.

>>> class Fib (object):

... def __init__ (self):

... self.a, self.b = 0, 1 # initialize a and b

... def __iter__ (self):

... return Self # returns the iteration object, which is itself an iterative object returned from its own

... def __next__ (self):

... self.a, self.b = self.b, SELF.A + self.b # calculate Next value

... if SELF.A > 10000: # exit loop condition

... raisestopiteration ();

... return SELF.A # returns the next value

...

>>> for N in Fib ():

... print (n)

...

1

1

2

3

5

8

13

21st

34

55

89

144

233

377

610

987

1597

2584

4181

6765

1.1.3   __getitem__

above The Fib instance feels like a list, but it is not possible to take an element by subscript.

You can do it by __getitem__ the method.

>>> class Fib (object):

... def __getitem__ (self, n):

... a, b = 1, 1

... for x in range (n):

... a, B = B, A + b

... return a

...

>>> f = Fib ()

>>> F[0]

1

>>> F[4]

5

>>> f[88]

1779979416004714189

1.1.4   __getattr__

Normally, when we call a method or property of a class, it will be an error if it does not exist.

>>> class Student (object):

... def __init__ (self):

... self.name = ' Daidai '

...

>>> s = Student ()

>>> Print (S.name)

Daidai

>>> Print (S.score)

Traceback (most recent):

File "<stdin>", line 1, in <module>

Attributeerror: ' Student ' object has Noattribute ' score '

plus __getattr__ Dynamic return property value

>>> class Student (object):

... def __init__ (self):

... self.name = ' Daidai '

... def __getattr__ (self, attr):-- python dynamically calls this method when the input score does not exist

... if attr = = ' Score ':

... return 98

...

>>> s = Student ()

>>> S.name

' Daidai '

>>> S.score

98

the __getattr__ return function is also possible

>>> class Student (object):

... def __getattr__ (self, attr):

... if attr = = ' age ':

... return lambda:24

...

>>> s = Student ()

>>> S.age

<functionStudent.__getattr__.<locals>.<lambda> at 0x2ac5ebc8e730>

>>> S.age ()

24

called only if no attribute is found __getattr__ , existing attributes, such as name, are not found in __getattr__ .

>>> class Student (object):

... def __getattr__ (self, attr):

... if attr = = ' age ':

... return lambda:24

... raise attributeerror (' \ ' student\ ' object has no attribute \ '%s\ '%attr)

...

>>>

>>> s = Student ()

>>> S.name

Traceback (most recent):

File "<stdin>", line 1, in <module>

File "<stdin>", line 5, in __getattr__

Attributeerror: ' Student ' object has noattribute ' name '

>>> S.age

<functionStudent.__getattr__.<locals>.<lambda> at 0x2ac5ebc8e488>

>>> S.age ()

24

1.1.5   __call__

the __call__ method can be invoked directly on the instance itself .

>>> class Student (object):

... def __init__ (self, name):

... self.name = name

... def __call__ (self):

... print (' My name is%s. '% self.name)

...

>>> s = Student (' Daidai ')

>>> s

<__main__. Student Object at0x2ac5ebc99748>

>>> S ()-- Direct Instance object invocation

My name is Daidai.

You can determine whether an object can be called by callable

>>>Callable (Student (' Daidai '))

True

>>> callable (max)

True

>>> Callable ((1, 2, 3))

False

>>> callable (' str ')

False

__call__ can also pass in Parameters

>>> class Student (object):

... def __init__ (self, name):

... self.name = name

... def __call__ (Self, others):

... print (' My name is%s,%s '% (Self.name, others))

...

>>>

>>> s = Student (' Daidai ')

>>> s (' so handsome. ')

My name is Daidai and so handsome.


This article is from the "90SirDB" blog, be sure to keep this source http://90sirdb.blog.51cto.com/8713279/1826210

Python object-oriented advanced programming--Custom classes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.