python
Turn a list or tuple to string
print ', '.join(str(x) for x in list_of_ints)
Or
print ', '.join([str(x) for x in list_of_ints])
The *args and **kwargs is a common idiom to allow arbitrary number of arguments to functions as described in the section more on defining functions in the Python documentation.
The *args will give you all function parameters as a tuple:
In [1]: def foo(*args):
…: for a in args:
…: print a
…:
…:
In [2]: foo(1)
1
In [4]: foo(1,2,3)
1
2
3
The **kwargs will give you all keyword arguments except for those corresponding to a formal parameter as a dictionary.
In [5]: def bar(**kwargs):
…: for a in kwargs:
…: print a, kwargs[a]
…:
…:
In [6]: bar(name=‘one’, age=27)
age 27
name one
Pasted from https://stackoverflow.com/questions/36901/what-does-double-star-and-star-do-for-parameters
Sometimes you might want to define a function that can take any number of parameters, i.e. variable number of arguments, this can be achieved by using the stars (save as function_varargs.py):
def total(a=5, *numbers, **phonebook):
print(‘a’, a)
#iterate through all the items in tuple
for single_item in numbers:
print(‘single_item’, single_item)
#iterate through all the items in dictionary
for first_part, second_part in phonebook.items():
print(first_part,second_part)
print(total(10,1,2,3,Jack=1123,John=2231,Inge=1560))
Output:
$ python function_varargs.py
a 10
single_item 1
single_item 2
single_item 3
Inge 1560
John 2231
Jack 1123
None
why-dict-getkey-instead-of-dictkey
It allows you to provide a default value if the key is missing:
dictionary.get(“bogus”, default_value)
returns default_value (whatever you choose it to be), whereas
dictionary[“bogus”]
would raise a KeyError.
If omitted, default_value is None, such that
dictionary.get(“bogus”) # <-- No default specified – defaults to None
returns None just like
dictionary.get(“bogus”, None)
what-is-the-difference-between-is-none-and-none
is will return True if two variables point to the same object, == if the objects referred to by the variables are equal.
There are two types of fields - class variables and object variables which are classified depending on whether the class or the object owns the variables respectively.
Class variables are shared - they can be accessed by all instances of that class. There is only one copy of the class variable and when any one object makes a change to a class variable, that change will be seen by all the other instances.
Object variables are owned by each individual object/instance of the class. In this case, each object has its own copy of the field i.e. they are not shared and are not related in any way to the field by the same name in a different instance. An example will make this easy to understand (save as oop_objvar.py):
class Robot:
“”“Represents a robot, with a name.”""
A class variable, counting the number of robots
population = 0
def init(self, name):
“”“Initializes the data.”""
self.name = name
print("(Initializing {})".format(self.name))
When this person is created, the robot
# adds to the population
Robot.population += 1
def die(self):
“”“I am dying.”""
print("{} is being destroyed!".format(self.name))
Robot.population -= 1
if Robot.population == 0:
print("{} was the last one.".format(self.name))
else:
print(“There are still {:d} robots working.”.format(
Robot.population))
def say_hi(self):
“”“Greeting by the robot.
Yeah, they can do that.”""
print(“Greetings, my masters call me {}.”.format(self.name))
@classmethod
def how_many(cls):
“”“Prints the current population.”""
print(“We have {:d} robots.”.format(cls.population))
droid1 = Robot(“R2-D2”)
droid1.say_hi()
Robot.how_many()
droid2 = Robot(“C-3PO”)
droid2.say_hi()
Robot.how_many()
print("\nRobots can do some work here.\n")
print(“Robots have finished their work. So let’s destroy them.”)
droid1.die()
droid2.die()
Robot.how_many()
Output:
$ python oop_objvar.py
(Initializing R2-D2)
Greetings, my masters call me R2-D2.
We have 1 robots.
(Initializing C-3PO)
Greetings, my masters call me C-3PO.
We have 2 robots.
Robots can do some work here.
Robots have finished their work. So let’s destroy them.
R2-D2 is being destroyed!
There are still 1 robots working.
C-3PO is being destroyed!
C-3PO was the last one.
We have 0 robots.
inheritance
class SchoolMember:
‘’‘Represents any school member.’’’
def init(self, name, age):
self.name = name
self.age = age
print(’(Initialized SchoolMember: {})’.format(self.name))
def tell(self):
‘’‘Tell my details.’’’
print(‘Name:"{}" Age:"{}"’.format(self.name, self.age), end=" ")
class Teacher(SchoolMember):
‘’‘Represents a teacher.’’’
def init(self, name, age, salary):
SchoolMember.init(self, name, age)
self.salary = salary
print(’(Initialized Teacher: {})’.format(self.name))
def tell(self):
SchoolMember.tell(self)
print(‘Salary: “{:d}”’.format(self.salary))
class Student(SchoolMember):
‘’‘Represents a student.’’’
def init(self, name, age, marks):
SchoolMember.init(self, name, age)
self.marks = marks
print(’(Initialized Student: {})’.format(self.name))
def tell(self):
SchoolMember.tell(self)
print(‘Marks: “{:d}”’.format(self.marks))
t = Teacher(‘Mrs. Shrividya’, 40, 30000)
s = Student(‘Swaroop’, 25, 75)
prints a blank line
print()
members = [t, s]
for member in members:
# Works for both Teachers and Students
member.tell()
Output:
$ python oop_subclass.py
(Initialized SchoolMember: Mrs. Shrividya)
(Initialized Teacher: Mrs. Shrividya)
(Initialized SchoolMember: Swaroop)
(Initialized Student: Swaroop)
Name:“Mrs. Shrividya” Age:“40” Salary: “30000”
Name:“Swaroop” Age:“25” Marks: “75”
request parameter
1.Construct query parameters, can use below two methods:
1).add ?parameter= in path, like area51ID is the query parameter
2).use params in post
2.Construct body parameter for request:
Use data parameter in post
data ={'name ': ‘jh’, ‘age’: 28}
Request.post(url, data=data)
3.Construct header parameter:
resp=Area51.go(
base_url+"/mufon/metadata/{}/{}/{}/".format(tag,mufon_key,ufos_with_key_fields),
headers={‘Content-Type’:‘text/plain’,‘userId’:user,‘securityToken’:cls.token})
4.Construct path parameter:
base_url+"/mufon/metadata/{}/{}/{}/".format(tag,key,key_fields)
class method vs static method in Python
Key Takeaways
• Instance methods need a class instance and can access the instance through self.
• Class methods don’t need a class instance. They can’t access the instance (self) but they have access to the class itself via cls.
• Static methods don’t have access to cls or self. They work like regular functions but belong to the class’s namespace.
• Static and class methods communicate and (to a certain degree) enforce developer intent about class design. This can have maintenance benefits.
Class Method
The @classmethod decorator, is a builtin function decorator that is an expression that gets evaluated after your function is defined. The result of that evaluation shadows your function definition.
A class method receives the class as implicit first argument, just like an instance method receives the instance
Syntax:
class C(object):
@classmethod
def fun(cls, arg1, arg2, …):
…
fun: function that needs to be converted into a class method
returns: a class method for function.
• A class method is a method which is bound to the class and not the object of the class.
• They have the access to the state of the class as it takes a class parameter that points to the class and not the object instance.
• It can modify a class state that would apply across all the instances of the class. For example it can modify a class variable that will be applicable to all the instances.
Static Method
A static method does not receive an implicit first argument.
Syntax:
class C(object):
@staticmethod
def fun(arg1, arg2, …):
…
returns: a static method for function fun.
• A static method is also a method which is bound to the class and not the object of the class.
• A static method can’t access or modify class state.
• It is present in a class because it makes sense for the method to be present in class.
Class method vs Static Method
• A class method takes cls as first parameter while a static method needs no specific parameters.
• A class method can access or modify class state while a static method can’t access or modify it.
• In general, static methods know nothing about class state. They are utility type methods that take some parameters and work upon those parameters. On the other hand class methods must have class as parameter.
• We use @classmethod decorator in python to create a class method and we use @staticmethod decorator to create a static method in python.
When to use what?
• We generally use class method to create factory methods. Factory methods return class object ( similar to a constructor ) for different use cases.
• We generally use static methods to create utility functions.
How to define a class method and a static method?
To define a class method in python, we use @classmethod decorator and to define a static method we use @staticmethod decorator.
Let us look at an example to understand the difference between both of them. Let us say we want to create a class Person. Now, python doesn’t support method overloading like C++ or Java so we use class methods to create factory methods. In the below example we use a class method to create a person object from birth year.
As explained above we use static methods to create utility functions. In the below example we use a static method to check if a person is adult or not.
Implementation
Python program to demonstrate
use of class method and static method.
from datetime import date
class Person:
def init(self, name, age):
self.name = name
self.age = age
# a class method to create a Person object by birth year.
@classmethod
def fromBirthYear(cls, name, year):
return cls(name, date.today().year - year)
# a static method to check if a Person is adult or not.
@staticmethod
def isAdult(age):
return age > 18
person1 = Person(‘mayank’, 21)
person2 = Person.fromBirthYear(‘mayank’, 1996)
print person1.age
print person2.age
print the result
print Person.isAdult(22)
Run on IDE
Output
21
21
True
classmethod is a descriptor, wrapping a function, and you can call the resulting object on a class or (equivalently) an instance thereof:
class x(object):
… def c1(*args): print ‘c1’, args
… c1 = classmethod(c1)
… @classmethod
… def c2(*args): print ‘c2’, args
…inst = x()
x.c1()
c1 (<class ‘main.x’>,)x.c2()
c2 (<class ‘main.x’>,)inst.c1()
c1 (<class ‘main.x’>,)inst.c2()
c2 (<class ‘main.x’>,)
As you see, whether you define it directly or with decorator syntax, and whether you call it on the class or the instance, the classmethod always receives the class as its first argument.
One of the main uses of classmethod is to define “alternative constructors”:class y(object):
… def init(self, astring):
… self.s = astring
… @classmethod
… def fromlist(cls, alist):
… x = cls(’’)
… x.s = ‘,’.join(str(s) for s in alist)
… return x
… def repr(self):
… return ‘y(%r)’ % self.s
…y1 = y(‘xx’)
y1
y(‘xx’)y2 = y.fromlist(range(3))
y2
y(‘0,1,2’)
Now if you subclass y, the classmethod keeps working, e.g.:class k(y):
… def repr(self):
… return ‘k(%r)’ % self.s.upper()
…k1 = k.fromlist([‘za’,‘bu’])
k1
k(‘ZA,BU’)
Decorators
In this introductory tutorial, we’ll look at what decorators are and how to create and use them. Decorators provide a simple syntax for calling higher-order functions.
By definition, a decorator is a function that takes another function and extends the behavior of the latter function without explicitly modifying it.
Sounds confusing—but it’s really not, especially after we go over a number of examples. You can find all the examples from this article here.
Free Bonus: Click here to get access to a free “The Power of Python Decorators” guide that shows you 3 advanced decorator patterns and techniques you can use to write to cleaner and more Pythonic programs.
Updates:
• 01/12/2016: Updated examples to Python 3 (v3.5.1) syntax and added a new example.
• 11/01/2015: Added a brief explanation on the functools.wraps() decorator.
Functions
Before you can understand decorators, you must first understand how functions work. Essentially, functions return a value based on the given arguments.
def foo(bar):
return bar + 1
print(foo(2) == 3)
First Class Objects
In Python, functions are first-class objects. This means that functions can be passed around, and used as arguments, just like any other value (e.g, string, int, float).
def foo(bar):
return bar + 1
print(foo)
print(foo(2))
print(type(foo))
def call_foo_with_arg(foo, arg):
return foo(arg)
print(call_foo_with_arg(foo, 3))
Nested Functions
Because of the first-class nature of functions in Python, you can define functions inside other functions. Such functions are called nested functions.
def parent():
print(“Printing from the parent() function.”)
def first_child():
return “Printing from the first_child() function.”
def second_child():
return “Printing from the second_child() function.”
print(first_child())
print(second_child())
What happens when you call the parent() function? Think about this for a minute. You should get…
Printing from the parent() function.
Printing from the first_child() function.
Printing from the second_child() function
Try calling the first_child(). You should get an error:
Traceback (most recent call last):
File “decorator03.py”, line 15, in
first_child()
NameError: name ‘first_child’ is not defined
What have we learned?
Whenever you call parent(), the sibling functions, first_child() and second_child() are also called AND because of scope, both of the sibling functions are not available (e.g., cannot be called) outside of the parent function.
Returning Functions
Python also allows you to return functions from other functions. Let’s alter the previous function for this example.
def parent(num):
def first_child():
return “Printing from the first_child() function.”
def second_child():
return “Printing from the second_child() function.”
try:
assert num == 10
return first_child
except AssertionError:
return second_child
foo = parent(10)
bar = parent(11)
print(foo)
print(bar)
print(foo())
print(bar())
The output of the first two print statements is:
<function first_child at 0x1004a8c08>
<function second_child at 0x1004a8cf8>
This simply means that foo points to the first_child() function, while bar points to the second_child() function.
The output of the second two functions confirms this:
Printing from the first_child() function.
Printing from the second_child() function.
Finally, did you notice that in example three, we executed the sibling functions within the parent functions - e.g, second_child(). Meanwhile in this last example, we did not add parenthesis to the sibling functions - first_child - upon returning so that way we can use them in the future. Make sense?
Now, my friend, you are ready to take on decorators!
Decorators
Let’s look at two examples …
Example 1
def my_decorator(some_function):
def wrapper():
print(“Something is happening before some_function() is called.”)
some_function()
print(“Something is happening after some_function() is called.”)
return wrapper
def just_some_function():
print(“Wheee!”)
just_some_function = my_decorator(just_some_function)
just_some_function()
Can you guess what the output will be? Try.
Something is happening before some_function() is called.
Wheee!
Something is happening after some_function() is called.
To understand what’s going on here, just look back at the four previous examples. We are literally just applying everything learned. Put simply, decorators wrap a function, modifying its behavior.
Let’s take it one step further and add an if statement.
Example 2
def my_decorator(some_function):
def wrapper():
num = 10
if num == 10:
print(“Yes!”)
else:
print(“No!”)
some_function()
print(“Something is happening after some_function() is called.”)
return wrapper
def just_some_function():
print(“Wheee!”)
just_some_function = my_decorator(just_some_function)
just_some_function()
This will output in:
Yes!
Wheee!
Something is happening after some_function() is called.
Syntactic Sugar!
Python allows you to simplify the calling of decorators using the @ symbol (this is called “pie” syntax).
Let’s create a module for our decorator
def my_decorator(some_function):
def wrapper():
num = 10
if num == 10:
print(“Yes!”)
else:
print(“No!”)
some_function()
print(“Something is happening after some_function() is called.”)
return wrapper
if name == “main”:
my_decorator()
Okay. Stay with me. Let’s look at how to call the function with the decorator:
from decorator07 import my_decorator
@my_decorator
def just_some_function():
print(“Wheee!”)
just_some_function()
When you run this example, you should get the same output as in the previous one:
Yes!
Wheee!
Something is happening after some_function() is called.
So, @my_decorator is just an easier way of saying just_some_function = my_decorator(just_some_function). It’s how you apply a decorator to a function.
Free Bonus: Click here to get access to a free the “The Power of Python Decorators” guide that shows you 3 advanced decorator patterns and techniques you can use to write to cleaner and more Pythonic programs.
Real World Examples
How about a few real world examples …
import time
def timing_function(some_function):
“”"
Outputs the time a function takes
to execute.
“”"
def wrapper():
t1 = time.time()
some_function()
t2 = time.time()
return “Time it took to run the function: " + str((t2 - t1)) + “\n”
return wrapper
@timing_function
def my_function():
num_list = []
for num in (range(0, 10000)):
num_list.append(num)
print(”\nSum of all the numbers: " + str((sum(num_list))))
print(my_function())
This returns the time before you run my_function() as well as the time after. Then we simply subtract the two to see how long it took to run the function.
Run it. Work through the code, line by line. Make sure you understand how it works.
from time import sleep
def sleep_decorator(function):
“”"
Limits how fast the function is
called.
“”"
def wrapper(*args, **kwargs):
sleep(2)
return function(*args, **kwargs)
return wrapper
@sleep_decorator
def print_number(num):
return num
print(print_number(222))
for num in range(1, 6):
print(print_number(num))
This decorator is used for rate limiting. Test it out.
One of the most used decorators in Python is the login_required() decorator, which ensures that a user is logged in/properly authenticated before s/he can access a specific route (/secret, in this case):
from functools import wraps
from flask import g, request, redirect, url_for
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if g.user is None:
return redirect(url_for(‘login’, next=request.url))
return f(*args, **kwargs)
return decorated_function
@app.route(’/secret’)
@login_required
def secret():
pass
Did you notice that the function gets passed to the functools.wraps() decorator? This simply preserves the metadata of the wrapped function.
Let’s look at one last use case. Take a quick look at the following Flask route handler:
@app.route(’/grade’, methods=[‘POST’])
def update_grade():
json_data = request.get_json()
if ‘student_id’ not in json_data:
abort(400)
# update database
return “success!”
Here we ensure that the key student_id is part of the request. Although this validation works it really does not belong in the function itself. Plus, perhaps there are other routes that use the exact same validation. So, let’s keep it DRY and abstract out any unnecessary logic with a decorator.
from flask import Flask, request, abort
from functools import wraps
app = Flask(name)
def validate_json(*expected_args):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
json_object = request.get_json()
for expected_arg in expected_args:
if expected_arg not in json_object:
abort(400)
return func(*args, **kwargs)
return wrapper
return decorator
@app.route(’/grade’, methods=[‘POST’])
@validate_json(‘student_id’)
def update_grade():
json_data = request.get_json()
print(json_data)
# update database
return “success!”
The wraps help keep the metadata of wrapped method f
from functools import wraps
def my_decorator(f):
… @wraps(f)
… def wrapper(*args, **kwds):
… print(‘Calling decorated function’)
… # add action here, eg log in check
… return f(*args, **kwds)
… return wrapper
…@my_decorator
… def example():
… “”“Docstring”""
… print(‘Called example function’)
…example()
Calling decorated function
Called example functionexample.name
‘example’example.doc
‘Docstring’
Without the use of this decorator factory, the name of the example function would have been ‘wrapper’, and the docstring of the original example() would have been lost.
本文介绍了Python中类变量、对象变量、类方法、静态方法的概念和使用,通过示例展示了如何定义和调用这些方法。同时,文章探讨了*args和**kwargs参数的作用,并解释了在函数中如何使用。最后,文章还讲解了装饰器的工作原理,包括如何创建和应用装饰器,以及装饰器在实际编程中的应用示例。
2093

被折叠的 条评论
为什么被折叠?



