#!/usr/bin/python
# Filename: class_init.py
class Person:
def __init__(self, name):
self.name = name
def sayHi(self):
print 'Hello, my name is', self.name
p = Person('Swaroop')
p.sayHi()
Hello, my name is Swaroop
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Singleton(object):
__instance = None # 定义实例
def __init__(self):
pass
def __new__(cls, *args, **kwd): # 在__init__之前调用
if Singleton.__instance is None: # 生成唯一实例
Singleton.__instance = object.__new__(cls, *args, **kwd)
return Singleton.__instance
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Fruit(object):
def __init__(self, color = "red", price = 0):
self.__color = color
self.__price = price
def __getattribute__(self, name): # 获取属性的方法
return object.__getattribute__(self, name)
def __setattr__(self, name, value):
self.__dict__[name] = value
if __name__ == "__main__":
fruit = Fruit("blue", 10)
print fruit.__dict__.get("_Fruit__color") # 获取color属性
fruit.__dict__["_Fruit__price"] = 5
print fruit.__dict__.get("_Fruit__price") # 获取price属性
#!/usr/bin/python
# -*- coding: UTF-8 -*-class FruitShop:
def __getitem__(self, i): # 获取水果店的水果
return self.fruits[i]
if __name__ == "__main__":
shop = FruitShop()
shop.fruits = ["apple", "banana"]
print shop[1]
for item in shop: # 输出水果店的水果
print item,
banana apple banana
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Fruit:
'''Fruit类''' #为Fruit类定义了文档字符串
def __str__(self): # 定义对象的字符串表示
return self.__doc__
if __name__ == "__main__":
fruit = Fruit()
print str(fruit) # 调用内置函数str()出发__str__()方法,输出结果为:Fruit类
print fruit #直接输出对象fruit,返回__str__()方法的值,输出结果为:Fruit类
#!/usr/bin/python
# -*- coding: UTF-8 -*-
class Fruit:
class Growth: # 内部类
def __call__(self):
print "grow ..."
grow = Growth() # 调用Growth(),此时将类Growth作为函数返回,即为外部类Fruit定义方法grow(),grow()将执行__call__()内的代码
if __name__ == '__main__':
fruit = Fruit()
fruit.grow() # 输出结果:grow ...
Fruit.grow() # 输出结果:grow ...
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有