Python基础--构造函数


记得吧,Python中有一个关键字叫self。

构造

class FooBar:
  def _int_(self):
    self.somevar = 42

>>>f = FooBar()
>>>f.somevar
42

重写

class A:
  def hello(self):
    print "Hello, I'm A"

class B(A):
  def hello(self):
    print "Hello, I'm B"

b = B()
b.Hello()
Hello, I'm B

属性

class Rectangle:
  def _init_(self):
    self.width = 0
    self.height = 0
  def setSize(sef, size):
    self.width, self.height = size
  def getSize(self):
    return self.width, self.height

使用:

r = Rectangle()
r.width = 10
r.height = 5
r.getSize() #(10, 5)
r.setSize(150, 100) #(150, 100)

Property函数
就是对上面的属性进行包装:

class Rectangle:
  def _init_(self):
    self.width = 0
    self.height = 0
  def setSize(sef, size):
    self.width, self.height = size
  def getSize(self):
    return self.width, self.height
  size = property(getSize, setSize)

使用:

r = Rectangle()
r.width = 10
r.height = 5
r.size #(10, 5)
r.size(150, 100) #(150, 100)

静态方法
装饰器@

class MyClass:
  @staticmethod
  def smeth():
    print 'This is a static method'

评论关闭