python杂记

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 sti

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值