Python小杂点

  1.函数调用

  a = []

  def fun(a):

         a.append(1)

  print (a)

  这个时候输出的结果为[],如果想要出现1,需要先运行函数fun,然后在输出a

  2.python方法

  def demo1(x):

    print ("my is one demo"+x)


  class A(object):
    def demo2(self,x):
      print ("AAAAAA")


    @classmethod
    def class_demo2(cls,x):
      print ("BBBBBB")


    @staticmethod
    def static_demo2(x):
      print ("CCCCCC")


  a = A()
  a.demo2(2)
  a.class_demo2(3)
  a.static_demo2(4)
  A.class_demo2(4)
  A.static_demo2(6)

  对于函数参数self和cls,其实是对类或者实例的绑定,对于一般的函数来说,我们直接使用demo(x)来调用,它的工作与类或实例无关。对于实例  方法,在类每次定义方法的时候都需要绑定这个实例,即demo2(self,x),为什么要这么做呢?因为实例方法的调用离不开实例,我们需要把实例  自己传递给函数,调用的时候是这样的a.demo2(x),其实是(demo2(a,x)),类方法也是一样的,只不过它传递的是类而不是实例,A.class_demo2(x)。  静态方法其实和普通方法一样,不需要对谁绑定,唯一的泣别是调用的时候需要使用a.static_demo2(x)或者A.static_demo2(x)来调用。

  3.类变量和实例变量

  name = "aaa"
  p1 = Person()
  p2 = Person()
  p1.name = "bbb"
  print (p1.name)
  print (p2.name)
  print (Person.name)

  类变量就是供类使用的变量,实例变量就是供实例使用的,p1.name="bbb",是实例调用了类变量,但是在实例的作用域里把类变量的引用改变了,就变成了一个实例变量。

  4.几个方法

  isinstance()

Fixes duplicate types in the second argument of isinstance(). For example, isinstance(x, (int, int)) is converted to isinstance(x, (int)).

  hasattr()

  hasattr(object, name)

The arguments are an object and a string. The result is True if the string is the name of one of the object’s attributes, False if not. (This is implemented by calling getattr(object, name) and seeing whether it raises an AttributeError or not.)

  getattr()

  getattr(object, name[, default])
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.
  5.下划线 

  class Myclass():
  def __init__(self):
  self.__superprivate = "Hello"
  self._semiprivate = ",world"
  mc = Myclass()
  print (mc._semiprivate)
  print (mc.__dict__)

  __demo__:一种约定,python内部的名字,用来区别其他自定义的命名,以防冲突

  __demo:一种约定,用来指定私有变量的一种方式

  6.字符串格式化:%和format

  name = lss

  "ni hao %s" %name

  但是如果name=(1,2,3),就必须这样写: "ni hao %s" %(name,)

原文地址:https://www.cnblogs.com/jiexialss/p/5888649.html