假设我有一个带有字符串实例属性的类.我应该使用""值或" 无"初始化此属性吗?好吗?
def __init__(self, mystr="")
self.mystr = mystr
Run Code Online (Sandbox Code Playgroud)
要么
def __init__(self, mystr=None)
self.mystr = mystr
Run Code Online (Sandbox Code Playgroud)
编辑:我认为如果我使用""作为初始值,我" 声明 "变量是字符串类型.然后我将无法再为其分配任何其他类型.我对吗?
编辑:我认为这里需要注意的是,我的建议是错误的.将另一种类型分配给变量没有问题.我喜欢S.Lott的评论:" 因为Python中的任何内容都没有被宣布",所以你并没有考虑到这一点. "
我正在寻找Python中的Command模式实现...(根据维基百科,
命令模式是一种设计模式,其中一个对象用于表示和封装稍后调用方法所需的所有信息.
)
我发现的唯一一件事就是Command Dispatch 模式:
class Dispatcher:
def do_get(self): ...
def do_put(self): ...
def error(self): ...
def dispatch(self, command):
mname = 'do_' + command
if hasattr(self, mname):
method = getattr(self, mname)
method()
else:
self.error()
Run Code Online (Sandbox Code Playgroud)
可能是我错了,但看起来这是两个不同的概念,它们偶然会有相似的名字.
我错过了什么吗?
使用UserDict类有什么好处?
我的意思是,如果不是,我真的得到了什么
class MyClass(object):
def __init__(self):
self.a = 0
self.b = 0
...
m = MyClass()
m.a = 5
m.b = 7
Run Code Online (Sandbox Code Playgroud)
我会写以下内容:
class MyClass(UserDict):
def __init__(self):
UserDict.__init__(self)
self["a"] = 0
self["b"] = 0
...
m = MyClass()
m["a"] = 5
m["b"] = 7
Run Code Online (Sandbox Code Playgroud)
编辑:如果我理解正确,我可以在两种情况下都在运行时向对象添加新字段?
m.c = "Cool"
Run Code Online (Sandbox Code Playgroud)
和
m["c"] = "Cool"
Run Code Online (Sandbox Code Playgroud) 我有静态类型语言的编程经验.现在用Python编写代码我觉得它的可读性有些困难.让我们说我有一个班级主持人:
class Host(object):
def __init__(self, name, network_interface):
self.name = name
self.network_interface = network_interface
Run Code Online (Sandbox Code Playgroud)
我不明白这个定义," network_interface "应该是什么.它是一个字符串,如" eth0 "还是一个类NetworkInterface的实例?我正在考虑解决这个问题的唯一方法是使用" docstring " 记录代码.像这样的东西:
class Host(object):
''' Attributes:
@name: a string
@network_interface: an instance of class NetworkInterface'''
Run Code Online (Sandbox Code Playgroud)
或者可能有类似的事情的名称约定?
我无法找到是否可以从Python中的静态方法调用非静态方法.
谢谢
编辑:好的.静电静电怎么样?我可以这样做:
class MyClass(object):
@staticmethod
def static_method_one(cmd):
...
@staticmethod
def static_method_two(cmd):
static_method_one(cmd)
Run Code Online (Sandbox Code Playgroud) 我在Python中发现了以下开源代码:
class Wait:
timeout = 9
def __init__(self, timeout=None):
if timeout is not None:
self.timeout = timeout
...
Run Code Online (Sandbox Code Playgroud)
我试图理解上面的代码是否有使用默认参数值的优点:
class Wait:
def __init__(self, timeout=9):
...
Run Code Online (Sandbox Code Playgroud) 我有一个方法,它要求另一个类的类方法
def get_interface_params_by_mac(self, host, mac_unified):
lines = RemoteCommand.remote_command(host, cls.IFCONFIG)
Run Code Online (Sandbox Code Playgroud)
...
class RemoteCommand(object):
@classmethod
def remote_command(cls, host, cmd, sh = None):
...
Run Code Online (Sandbox Code Playgroud)
我要为get_interface_params_by_mac方法编写一个单元测试,我想在其中更改remote_command的实现(我认为它调用存根 - 如果我错了就修复我)
在Python中用什么方法做到这一点?