Contents
- The Magic of Objects
- Class
- 1. What Is a Class, Exactly?
- 2. Making your own classes
- 3. Attributes, Fuctions and Methods
- 4. Privacy Revisited
- 5. lambda
- 6. Specifying a Superclass
- 7. issubclass()
- 8. Attribute bases
- 9. isinstance()
- 10. __ class__ attribute
- 11. Multiple inheritance
- 12. Previous on eval(str)
- 13. Variables in python
- 14. hasattr(object, attribute)
- 15. getattr(object, attribute, default value)
- 16. Use callable() to check whether an attribute is callable
- 17. object.__ dict__ attribute
- 18. Abstract base classes
- 19. abstractclass.register(class)
- 20. setattr(object, attribute, value)
- 21. Summary
The Magic of Objects
- In object-oriented programming, the term object loosely refers to
a collection of data ( attribute) with a set of methods to access and manipulate them
. - Some of the most important benefits of objects include followings:
(1)Polymorphism
(2)Encapsulation
(3)Inheritance
1. Polymorphism
- The term polymorphism is derived from a Greek word meaning “having multiple forms.” Basically, that means that
even if you don’t know what kind of object a variable refers to, you may still be able to perform operations on it that will work differently depending on the type (or class) of the object
.
(1) First example
from random import choice
x=choice(['hello,world',[1,2,'e','e',4,5]])# choice()
x.count('e')# sequence.count(element)
>>>2
choice()
In the standard library module random, function choice(sequence) randomly return a element of the sequence.
count()
For a sequence (list, string, tuple), sequence.(element) returns how many times the element shows up in the sequence,
- x can contain either the string ‘Hello, world!’ or the list [1, 2, ‘e’, ‘e’, 4,5], you don’t know, and you don’t have to worry about it. All you care about is how many times you find ‘e’ in x, and you can find that out regardless of whether x is a list or a string.
(2) Second example
def length_message(x):
print('The length of',repr(x),'is',len(x))
y='hello,world'
z=[1,1,2,3,5,8,13,21]
length_message(y)
length_message(z)
>>>The length of 'hello,world' is 11
>>>The length of [1, 1, 2, 3, 5, 8, 13, 21] is 8
repr is one of the grand masters of polymorphism—it workswith anything
.
repr()
Return the represent of any object as a string.
2. Encapsulation
- Encapsulation is the principle of hiding unnecessary details from the rest of the world.
3. Inheritance
Class
1. What Is a Class, Exactly?
- Class is a kind of object. All objects belong to a class and are said to be
instances of that class
.
2. Making your own classes
class Person():
def set_name(self,name):
self.name=name # self.name make the class have an attribute named name
def get_name(self):
print(self.name)
def greeting(self):
print('Hello,{}!'.format(self.name))
first=Person()# this is how you construct a object( instance) of a class
second=Person()
first.set_name('Luke Skywalker')
second.set_name('Anakin Skywalker')
first.get_name()
second.get_name()
first.greeting()
second.greeting()
>>>Luke Skywalker
Anakin Skywalker
Hello,Luke Skywalker!
Hello,Anakin Skywalker!
- All the method of a class must have the parameter
self
so that the methods can have access to the object itself whose attributs they are supposed to manipulate. self.name make the class have an attribute named name
.The attribute name can be access from outside the class
.
first.name='Yoda'
first.get_name()
first.greeting()
>>>Yoda
>>>Hello,Yoda!
3. Attributes, Fuctions and Methods
The self parameter (mentioned in the previous section) is, in fact, what distinguishes methods from functions
. Methods (or, more technically, bound methods) have their first parameter bound to the instance they belong to, so you don’t have to supply it. In class definitions, the method must have self as one of its parameters, andinside the methods
you have to useself.attr
to refer tothe attributes of the class
. When attributes used inside the class but outside the methods, the name alone will work well.
4. Privacy Revisited
- By default,
you can access the attributes of an object from the “outside”
, which may raise problems sometimes. For example, ClosedObject may send an e-mail message to some administrator every time an object changes its name. This could be part of the set_name method. But what happens when you set c.name directly? Nothing happens—no e-mail message is sent. To avoid this sort of thing, you have private attributes.These are attributes that are not accessible outside the object; they are accessible only through
accessormethods, such as get_name and set_name
. - To make a
method
orattribute
private (inaccessible from the outside), simplystart its name with two underscores
.
(1) private attributes
class Person():
def set_name(self,name):
self.__name=name# prvite attribute
def get_name(self):
print(self.__name)
def greeting(self):
print('Hello,{}!'.format(self.__name))
first=Person()
second=Person()
first.set_name('Luke Skywalker')
second.set_name('Anakin Skywalker')
first.get_name()
second.get_name()
first.greeting()
second.greeting()
>>>
Luke Skywalker
Anakin Skywalker
Hello,Luke Skywalker!
Hello,Anakin Skywalker!
first.__name='Yuda'
first.get_Luke()
>>>
Luke Skywalker# the name hasn't changed
(2) private methods
class Secretive:
def __inaccessible(self):
print('Bet you cannot see me...')
def accessible(self):
print('The secret is: ')
self.__inaccessible()
secret=Secretive()
secret.__inaccessible()
>>>
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-37-ea73264a6ffb> in <module>()
6 self.__inaccessible()
7 secret=Secretive()
----> 8 secret.__inaccessible()
9
AttributeError: 'Secretive' object has no attribute '__inaccessible'
secret.accessible()
>>>
The secret is:
Bet you cannot see me...
You can still access the private method and attribute by adding a single underscore and the class name to the beginning
.
secret._Secretive__inaccessible()
>>>
Bet you cannot see me...
5. lambda
Description of lambda
lambda parameters: returns
- lambda is used when you need a function without too much effort to define it. And it is called anonymous function.
list1 = [3,5,-4,-1,0,-2,-6]
sorted(list1, key=lambda x: abs(x))# sort the list by the absolute values of elements
>>>
[0, -1, -2, 3, -4, 5, -6]
sorted()
- list.sort(): sort in place without returning
- built-in sorted:
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
(1)iterable: iterable object
(2)key: according to the properties or functions of elements to .
(3)reverse: TRUE sort in descending order, False sort in ascending order.
sorted returns the same iterable object as the parameter
.
6. Specifying a Superclass
- Subclasses expand on the definitions in their superclasses. You indicate the superclass in a class statement by writing it in parentheses after the class name.
class Filter:
def init(self):
self.blocked=[]
def filter(self,sequence):
return [x for x in sequence if x not in self.blocked]
class SPAMFilter(Filter):
def init(self):
self.blocked=['SPAM']
f=Filter()
f.init() # have to initiate the object if the class has a init()
f.filter([1,2,3])
>>>
[1, 2, 3]
sf=SPAMFilter()
sf.init()
sf.filter(['SPAM', 'SPAM', 'SPAM', 'SPAM', 'eggs', 'bacon', 'SPAM'])
>>>
['eggs', 'bacon']
- For a class with a init() method, you have to first call the init() to initiate the object.
object sf rewrite the method init() and inheritant the method filter()
.
7. issubclass()
- If you want to find out whether a class is subclass of another, you can use the built-in function issubclass() which returns
True
orFalse
. issubclass(subclass, superclass)
issubclass(SPAMFilter,Filter)
>>>
True
issubclass(Filter,SPAMFilter)
>>>
False
8. Attribute bases
- Use attribute
__bases__
to find out the base class. class.__bases__
SPAMFilter.__bases__
>>>
(__main__.Filter,) # return a tuple
9. isinstance()
- You can check whether an object is an instance of a class by using
isinstance()
. isinstance( object, class)
isinstance(sf,SPAMFilter)
>>>
True
- sf is an direct object of SPAMFilter, and it is also a indirect object of Filter, because the relationship of SPAMFilter and Filter.
isinstance(sf,Filter)
>>>
True
10. __ class__ attribute
- Find out the class to which the object belongs.
object.__class__
sf.__class__
>>>
__main__.SPAMFilter
- Attention!!!: the difference of class__bases__ and object.__ class__
11. Multiple inheritance
- A class inherits from multiple superclasses.
class Calculator:
def calculate(self,expression):
self.value=eval(expression)# eval(str)
class Talker:
def talk(self):
print('The result of the expression is : ',self.value)
class TalkingCalculator(Calculator,Talker):
pass
tc=TalkingCalculator()
tc.calculate('1+35*64-99')
tc.talk()
>>>
The result of the expression is : 2142
- If you are using multiple inheritance, there is one thing you should look out for:
if a method is implemented differently by two or more of the superclasses (that is, you have two different methods with the same name), you must be careful about the order of these superclasses (in the class statement). The methods in the earlier classes override the methods in the later ones
12. Previous on eval(str)
eval(str
:take string as a vaild expression of python, calculating and returning the value
.
python=23
eval('python')
>>>
23
eval('tc')
>>>
<__main__.TalkingCalculator at 0x245e93d8748>
13. Variables in python
Every thing in python is object. All the varibles in python are reference variables that refer to objects.
14. hasattr(object, attribute)
hasattr(object, attribute)
:to check whether a object has a certain attribute(including method
).
hasattr(tc, 'talk')# supply the attrbute name as a string
>>>
True
supply the attrbute name as a string
15. getattr(object, attribute, default value)
getattr(object, attribute, default value)
: return a certain attribute of an object
, and also supply a default value that will be used if the attribute is not existed
. This function is usually used in if statement
.
getattr(tc,'talk',None)
>>>
<bound method Talker.talk of <__main__.TalkingCalculator object at 0x00000245E93E4FD0>>
16. Use callable() to check whether an attribute is callable
callable(getattr(tc,'talk',None))
>>>
True
callable() has to be used with getattr()
17. object.__ dict__ attribute
If you want to see all the values stored in an object, you can examine its __dict__
attribute.
18. Abstract base classes
- In general, an abstract class is simply one that can’t, or at least shouldn’t, be instantiated.
- Its job is to provide a set of abstract methods that subclasses should implement.
- abc module provides support for abstract base classes.
from abc import ABC,abstractmethod
class talker_2(ABC):
@abstractmethod #decorator
def talk(self):
pass
- Use a decoretor @abstractor to mark the abstract method----method that must be
implemented in a subclass.
t=Talker_2()
>>>
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-42-4e53a5e5dad5> in <module>()
----> 1 t=Talker_2()
TypeError: Can't instantiate abstract class Talker_2 with abstract methods talk
class Higet(Talker_2):
pass
h=Higet()
>>>
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-49-8fc6e10b4fe7> in <module>()
2 def show(self):
3 pass
----> 4 h=Higet()
TypeError: Can't instantiate abstract class Higet with abstract methods talk
If the subclass does not override the abstract method, it is still a abstract class which cannot be instantiateed
.
class Higet(Talker):
def talk(self):
print("Hi!")
h=Higet()
19. abstractclass.register(class)
abstractclass.register(class)
class Helloget:
def talk(self):
ptint('hello')
h1=Helloget()
isinstance(h1,Talker_2)
>>>
False
Talker_2.register(Helloget)
>>>
__main__.Helloget
isinstance(h1,Talker_2)
>>>
True
register the non-Talker_2 class Helloget as a subclass of abstract class Talker_2.
20. setattr(object, attribute, value)
Sets the given attribute of the objectto
value
21. Summary
When determining which classes you need and which methods they should have, you may try somethinglike this:
-
Write down a description of your problem (what should the program do?).
Underline all the nouns, verbs, and adjectives. -
Go through the nouns, looking for potential classes.
-
Go through the verbs, looking for potential methods.
-
Go through the adjectives, looking for potential attributes.
-
Allocate methods and attributes to your classes.