python类重载构造函数_Python:重载构造函数的问题

这篇博客针对具有Java背景的读者,介绍了Python中类的构造函数重载。通过示例`Computer`类,展示了如何使用`__init__`方法初始化实例变量,并利用默认参数实现类似Java中构造函数重载的功能。同时,提到了Python中静态变量的概念,以及`self`参数的重要性。
摘要由CSDN通过智能技术生成

我将假设您来自Java-ish背景,因此需要指出一些关键的区别.

class Computer(object):

"""Docstrings are used kind of like Javadoc to document classes and

members. They are the first thing inside a class or method.

You probably want to extend object, to make it a "new-style" class.

There are reasons for this that are a bit complex to explain."""

# everything down here is a static variable, unlike in Java or C# where

# declarations here are for what members a class has. All instance

# variables in Python are dynamic, unless you specifically tell Python

# otherwise.

defaultName = "belinda"

defaultRes = (1024, 768)

defaultIP = "192.168.5.307"

def __init__(self, name=defaultName, resolution=defaultRes, ip=defaultIP):

"""Constructors in Python are called __init__. Methods with names

like __something__ often have special significance to the Python

interpreter.

The first argument to any class method is a reference to the current

object, called "self" by convention.

You can use default function arguments instead of function

overloading."""

self.name = name

self.resolution = resolution

self.ip = ip

# and so on

def printStats(self):

"""You could instead use a __str__(self, ...) function to return this

string. Then you could simply do "print(str(computer))" if you wanted

to."""

print "Computer Statistics: --------------------------------"

print "Name:" + self.name

print "IP:" + self.ip

print "ScreenSize:" , self.resolution //cannot concatenate 'str' and 'tuple' objects

print "-----------------------------------------------------"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值