cqlinx 发表于 2017-4-26 12:56:39

Python中类的使用

  #coding=utf8'''Created on 2011-6-12@author: hufei'''name = 'hufei'if not name:passelse:class Person:                                       # class can be defined in a branch of 'if' statementdef __init__(self,name,age):self.name = nameself.age = agedef __str__(self):return u"%s:%d" % (self.name, self.age)def say_hello(self):print 'Hello'def say_hi(name):print u"%s:hi" % namedef say_hello(name):print u"%s: hello!" % namemaimai = Person('maimai',22)#attributes need not be declared, they spring into existence when they are first assignedmaimai.sex = 'Female'         print maimai                  #invoke __str__print maimai.sexprint type(maimai.age)print type(maimai.say_hello)    # <type 'instancemethod'>maimai.say_hello = say_hi       # methodname just looks like a reference, can be modifiedmaimai.say_hello('Jack')maimai.say_hi = say_hello       # method of Class can be added dynamicallymaimai.say_hi('Tom')
  python中的类的语法与java相比,灵活多变。相比而言,java是严格而规范的语言,而python给人更加随意的感觉。
页: [1]
查看完整版本: Python中类的使用