In the last part, we have learned some basic knowledge of object-oriented , This time, we will learn some advanced knowledge about the following objects ( Although I don't know what eggs are for ).

Static methods

A static method is a common function , In the namespace of the class definition , It does not operate on any instance type . Use decorators @staticmethod Define static methods . Class objects and instances can call static methods ;

Said so much , I guess it's going to be a bit of a muddle , Let's go straight to the code and see how to use static methods !

1. Write the code according to the normal logic and add @staticmethod Define static methods eat:

class People(object):
def __init__(self,name):
self.name = name @staticmethod # hold eat Method to static method
def eat(self):
print("%s is eating" % self.name) d = People("cc")
d.eat()

Run the above code , We will find the following errors :

TypeError: eat() missing 1 required positional argument: 'self'

----------eat Need one self Parameters , But it was called without passing

so... We can come to a conclusion :eat After becoming a static method , When it is called through an instance, it will not automatically pass the instance itself as a parameter to self

2. terms of settlement :

1) The instance itself is actively passed to the eat Method , namely d.eat(d)

class People(object):
def __init__(self, name):
self.name = name @staticmethod # hold eat Method to static method
def eat(self):
print("%s is eating" % self.name)
d = People("cc")
d.eat(d)
#------ Printout ------
#cc is eating

2) stay eat Remove from the method self Parameters ( It also means that , stay eat You can't go through self. Call other variables in the instance )

class People(object):
def __init__(self, name):
self.name = name @staticmethod # hold eat Method to static method
def eat():
print("%s is eating" % self.name) d = People("cc")
d.eat()
#------------------ Printout ----------------
#print("%s is eating" % self.name)
#NameError: name 'self' is not defined

Class method

A class method is a method that operates on the class itself as an object . Class methods use @classmethod Decorator definition , The first parameter is the class , The agreement is written as cls. Class objects and instances can call class methods .

The difference between class methods and normal methods is , Class methods can only access class variables , Cannot access instance variables .

It's still the same code , hold eat Turn it into a class method :

class People(object):
def __init__(self, name):
self.name = name @classmethod # hold eat Methods become class methods
def eat(self):
print("%s is eating" % self.name) d = People("cc")
d.eat()
--------------- Printout -------------------
print("%s is eating" % self.name)
AttributeError: type object 'People' has no attribute 'name'

Wrong statement :People No, name attribute ;

It said , Class methods can only access class variables , Cannot access instance variables , and name Here is the instance variable .

Let's try adding a class variable :

class People(object):
name = " Class variables "
def __init__(self, name):
self.name = name @classmethod # hold eat Methods become class methods
def eat(self):
print("%s is eating" % self.name) d = People("cc")
d.eat()
-------------------- Printout -------------------
Class variables is eating

Attribute method

The function of the attribute method is to pass through @property Turn a method into a static property ;

It's still the same code as before , hold eat Methods become static properties, see the effect :

class People(object):
name = " Please call me class variable "
def __init__(self, name):
self.name = name @property # hold eat Method becomes a static property
def eat(self):
print("%s is eating" % self.name) d = People("cc")
d.eat() ----------------- Printout --------------------
d.eat()
TypeError: 'NoneType' object is not callable

This is because eat Has become a static property , Of course, it can't be used any more () To call , Let's call it directly :

d.eat
------------- Printout ------------
cc is eating

Reflection

1. The definition of reflection

According to the form of string to operate members in an object

  • Look for members in an object according to the form of a string
  • Set members in an object according to the form of a string
  • Delete a member from an object in the form of a string
  • According to the form of a string to determine whether a member exists in an object

2. The function of reflection

  • getattr(object, name[, default])

Look for members in an object according to the form of a string

class People(object):
def __init__(self):
self.name = 'cc'
def eat(self):
return 'HI'
d = People()
ret1 = getattr(d,'eat')
ret2 = getattr(d,'name')
r1 = ret1()
print(r1)
print(ret2) -------------- Printout ----------------
HI
cc
  • setattr(object, name, value)

Set members in an object according to the form of a string

class People(object):
def __init__(self):
self.name = 'cc'
def eat(self):
return 'HI'
d = People()
set1 = setattr(d,'age',18)
r1 = getattr(d,'age')
print(r1) ----------------------- Printout ---------------------------
18
  • delattr(object, name)

Delete a member from an object in the form of a string

class People(object):
def __init__(self):
self.name = 'cc'
def eat(self):
return 'HI'
d = People()
del1 = delattr(d,'name')
r1 = getattr(d,'name')
print(r1) ---------------- Printout -------------------
AttributeError: 'People' object has no attribute 'name'
  • hasattr(object, name)

According to the form of a string to determine whether a member exists in an object

class People(object):
def __init__(self):
self.name = 'cc'
def eat(self):
return 'HI'
d = People()
h1 = hasattr(d,'age')
h2 = hasattr(d,'name')
print(h1,h2) --------------- Printout -----------------
False True

exception handling ( The lack of else and finally)

In the process of learning before, we will be exposed to all kinds of error information , In order to increase friendliness in the programming process , Can grab the corresponding error and give prompt information .

Common exceptions :

AttributeError Trying to access a tree that an object does not have , such as foo.x, however foo There is no attribute x
IOError Input / Abnormal output ; Basically can't open file
ImportError Cannot import module or package ; It's basically a path problem or a name error
IndentationError Grammar mistakes ( Subclasses of ) ; The code is not properly aligned
IndexError Subscript index out of sequence boundary , For example, when x There are only three elements , But try to visit x[5]
KeyError Trying to access a key that doesn't exist in the dictionary
KeyboardInterrupt Ctrl+C Pressed
NameError Use a variable that has not been assigned to an object
SyntaxError Python Illegal code , The code can't compile ( I think it's a grammatical mistake , Write the wrong )
TypeError The type of the incoming object does not meet the requirements
UnboundLocalError Trying to access a local variable that has not been set , Basically because there's another global variable with the same name ,
Leading you to think you're visiting it
ValueError Pass in a value that the caller doesn't expect , Even if the type of value is correct

More exceptions :

ArithmeticError
AssertionError
AttributeError
BaseException
BufferError
BytesWarning
DeprecationWarning
EnvironmentError
EOFError
Exception
FloatingPointError
FutureWarning
GeneratorExit
ImportError
ImportWarning
IndentationError
IndexError
IOError
KeyboardInterrupt
KeyError
LookupError
MemoryError
NameError
NotImplementedError
OSError
OverflowError
PendingDeprecationWarning
ReferenceError
RuntimeError
RuntimeWarning
StandardError
StopIteration
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
Warning
ZeroDivisionError

Common exception examples :

IndexError( Output the specified error message and print the error message )

dic = [1,2]
try:
dic[2]
except IndexError as e :
print("i got it!\n",e) --------------------------- Printout --------------------------
i got it!
list index out of range

KeyError( Output the specified error message and print the error message )

dic = {'name':'cc'}
try:
dic['age']
except KeyError as e :
print("i got it!\n",e) --------------------------- Printout ---------------------------
i got it!
'age'

ValueError

s1 = 'hello'
try:
int(s1)
except ValueError as e:
print (e) --------------------------- Printout ----------------------------
invalid literal for int() with base 10: 'hello'

Omnipotent abnormality Exception:( Not recommended for use , Not easy to debug ; Can be used with exception )

s1 = 'hello'
try:
int(s1)
except KeyError as e:
print(' Key error ')
except IndexError as e:
print(' Index error ')
except Exception as e:
print(' error ')

Custom exception :

class ccException(Exception):
def __init__(self,msg):
self.msg = msg
def __str__(self):
return self.msg
try:
raise ccException(" My abnormality ")
except ccException as e:
print(e) 

python Learning notes -( 11、 ... and ) Object-oriented progression & More articles on exception handling

  1. python Study notes 11 SQLALchemy ORM( Advanced )

    SqlAlchemy ORM SQLAlchemy yes Python A programming language ORM frame , The framework is built on a database API above , Use relational object maps for database operations , In short : Converts an object to SQL, And then use the data A ...

  2. python Learning Notes 6 Object oriented and related ( The basic chapter )

    Basic knowledge of object oriented : Object oriented is a way of programming , The implementation of this programming method is based on class and object Use class It's a template , There are several packages in the template “ function ” For use ( You can encapsulate variables common to multiple functions into objects ) object , Created from a template ...

  3. python Learning notes 7 object-oriented programming

    One . summary Process oriented : Write base code from top to bottom according to business logic Functional expression : Encapsulate a function code into a function , No need to write again in the future , Just call the function object-oriented : Classify and encapsulate functions , Let's develop " Faster, better, stronger ..." ...

  4. python Study notes 13 JQuery( Advanced )

    jQuery It's a JavaScript library . jQuery Greatly simplified JavaScript Programming . install jQuery There are two versions jQuery Available for download : Production versio ...

  5. python Learning notes _week6_ object-oriented

    object-oriented Introduce ( characteristic (class.object---> encapsulation . Inherit , polymorphic )).---> The world all things , All can be classified : The world all things , All can be targeted As long as it's an object , It must belong to a certain category : As long as it's an object , There must be attributes You are on ...

  6. Python Object oriented programming of learning notes ( 3、 ... and )Python Class magic method

    python There are some methods in the class that have two underscores before and after , These functions are called magic methods . These methods have special uses , Some don't need our own definition , Some can achieve more magical functions through some simple definitions I mainly divide them into three parts , The following is also divided into ...

  7. Python Learning notes 016—— object-oriented

    Object oriented is to describe an object with a class ( example ), Use classes to establish the relationship between instances object : object      example : instance 1 class 1.1 What is a class? Class is a tool for describing objects , You can create one or ...

  8. python Learning notes ( 7、 ... and ): object-oriented programming 、 class

    One . object-oriented programming object-oriented --Object Oriented Programming, abbreviation oop, It's a kind of programming idea . Before we talk about object orientation , Let's talk about the programming paradigm first , Programming paradigm, how do you program , To achieve a ...

  9. python Learning notes (6)-- Object oriented learning

    Content of this section :   Introduction to object-oriented programming Why object-oriented development ? Object oriented features : encapsulation . Inherit . polymorphic class . Method .   introduction You are now a developer of a game company , Now we need you to develop a model called ( Man dog war ) The game of , You just think ...

  10. python Learning notes (10): object-oriented

    One . Classes and instances 1. class (Class):  A collection of objects with the same properties and methods . It defines the properties and methods that are common to each object in the collection . Object is an instance of a class . 2. object : Data structure instance defined by class . Object contains two data members ( ...

Random recommendation

  1. Bumpy road :ASP.NET 5 Identity Authentication ( Part I )

    It's the first episode , Because I didn't solve the problem , The purpose of writing this blog is to record my problems , Lest I forget , Actually, I've almost forgotten , The process of writing is also the process of self review , And before collecting about ASP.NET 5 Authentication Bookmarks ...

  2. Abundant Resources

    https://github.com/vhf/free-programming-books/blob/master/free-programming-books-zh.md

  3. Freescle cortex-A9( Improving ...)

    key word :cortex-A9 , udoo ,mars board ; ( Content reference , Freescale's official website , If you have any questions, please contact me ) i.MX 6 The series processor introduces the industry's first truly scalable multi-core platform , Including based on ARM ...

  4. Codeforces Round #197 (Div. 2) : E

    I saw codeforces After the explanation written by the great God on , I know the essence of this question ! But compared with the previous two questions , The thinking of this problem is a little more difficult : But thinking about the essence of water , It's really not difficult : Method , It's like peeling an onion , From the outside to the inside : therefore ...

  5. CSS+Javascript The framework of

    CSS CSS Make a frame SASS http://www.oschina.net/p/sass Blueprint  http://www.oschina.net/p/blueprintcss Ela ...

  6. MAC OX To configure JDK environment variable

    Everyone in windows It's equipped with JDK Environment variables are easy , But if it's in mac It's equipped with JDK Environment variables and windows It's different inside , As follows : First of all : mac OS It comes with jdk, But is 1.6 Version of , Now a lot of people make it ...

  7. Android Analysis of the implementation mechanism of long press event in the system

    stay Android In the touch message , Three types of monitoring have been implemented , They are 1)pre-pressed: The corresponding semantics is user touch (tap) The screen 2)pressed: The corresponding semantics is user click (press) The screen 3)lon ...

  8. Page caching OutputCache

    Update page cache OutputCache   Why use OutputCache In my submission OutputCache It's the simplest caching technology , It's for page level , A simple instruction can achieve the effect of caching , Effectively lighten the server ...

  9. position:absolute In depth discussion of

    position:absolute The question of who to refer to for positioning . You might have thought that if absolute The parent of the element ( grandfather ) Element is not set position When attributes , Of this element position:absolute Huishen ...

  10. 246 ,Bootstrap Pop up box and warning box plug-ins

    Bootstrap Pop up box and warning box plug-ins Learning points : 1. pop-up 2. Warning box In this lesson, we mainly study Bootstrap Pop up box and warning box plug-ins in . One . pop-up Pop up box is to click an element to pop up a ...