Python入门(简明Python教程)——午

类与对象

1.在python中self类似于this指针,但是不可省略的,这是类内与类外的唯一区别标识。

2.self是对象方法的第一个参数,而cls是类方法的第一个参数,而staticmethod方法则无参数

3.类变量——对象变量

4.默认成员都是共有的,除非成员名以双下划线"__"开头,则会被认为是私有的

5.类后括号内为继承类,若无继承类,则无括号

class A(object):
    def foo1(self):
        print "Hello",self
    @staticmethod
    def foo2():
        print "hello"
    @classmethod
    def foo3(cls):
        print "hello",cls
# class Person:
#     pass
#
# p=Person()
# print(p)

class Person:
    def __init__(self,name):
        self.name=name
    def say_hi(self):
        print('hello,how are you?',self.name)

p=Person('Swaroop')
p.say_hi()

结果:

hello,how are you? Swaroop
class Person:
    population=0;
    def __init__(self,name):
        self.name=name
        Person.population+=1
    def say_hi(self):
        print('hello,how are you?',self.name)
        
    @classmethod
    def how_many(cls):
        """来自机器人的问候
        
        你可以的"""
        print("Greeting!{}".format(cls.population))

注意到“@classmethod”即函数方法“how_many”为类方法而非函数方法,是静态的。

装饰器

@func=timeit(func)

多重修饰:

def makeBold(fun):
    print('----a----')

    def inner():
        print('----1----')
        return '' + fun() + ''

    return inner


def makeItalic(fun):
    print('----b----')

    def inner():
        print('----2----')
        return '' + fun() + ''

    return inner


@makeBold
@makeItalic
def test():
    print('----c----')
    print('----3----')
    return 'hello python decorator'


ret = test()
print(ret)
----b----
----a----
----1----
----2----
----c----
----3----
hello python decorator

你可能感兴趣的:(python一次学习)