我正在使用RawConfigParser
来读取和更新 ini 样式的配置文件。这在标准配置中完全没有问题。我的问题是我在同一个脚本中读取不同的配置文件。无需过多赘述,当我阅读第二个配置文件时,它的值与第一个 ini 文件合并。
两个 ini 文件的原始内容
infile_1.ini
[section]
option = Original value
extraoption = not in ini file 2
inifile_2.ini
[section]
option = Original value
Run Code Online (Sandbox Code Playgroud)
这是我用来更改 ini 文件内容的代码。这是重现问题的一小段代码
import ConfigParser
class status_file:
myConfig = ConfigParser.RawConfigParser()
myConfig.optionxform = str
def __init__(self, str_statusfile):
self.myConfig.read( str_statusfile)
self.statusfile = str_statusfile
def option(self, new_value):
self.myConfig.set("section","option",new_value)
with open( self.statusfile, "w") as ini_out:
self.myConfig.write( ini_out )
statusfiles = ['inifile_1.ini', 'inifile_2.ini']
for myStatus in statusfiles:
myConfig = status_file(myStatus)
myConfig.option("Something new")
Run Code Online (Sandbox Code Playgroud)
执行此代码后,ini 文件的内容已按预期更改。但是在第二个 ini 文件中,合并了第一个 …
如果我定义一个简单的类
class someClass():
var = 1
x = someClass()
someClass.var = 2
Run Code Online (Sandbox Code Playgroud)
这将使x.var
等于 2。这是令人困惑的,因为通常类似于这样的东西:
a = 1
b = a
a = 2
Run Code Online (Sandbox Code Playgroud)
将保持 b 完好无损b==1
。那么为什么这与类变量不同呢?区别在哪里?可以调用所有类变量可变吗?在某种程度上,类变量的工作更像是将列表分配给a=[1]
并执行a[0]=2
.
基本上问题是如何x.var
访问 someClass.var 它必须是不同的,然后在 python 中将两个变量设置为相等时使用。怎么了?
基本上是这样的:
DEFAULT_TIMEOUT = 10
# or even: from my_settings import DEFAULT_TIMEOUT
def get_google(timeout=DEFAULT_TIMEOUT):
return requests.get('google.com', timeout=timeout)
Run Code Online (Sandbox Code Playgroud)
我认为只要常数确实保持不变,就应该可以正常工作。但我有时会看到这样的模式:
DEFAULT_TIMEOUT = 10
def get_google(timeout=None):
if timeout is None:
timeout = DEFAULT_TIMEOUT
return requests.get('google.com', timeout=timeout)
Run Code Online (Sandbox Code Playgroud)
这些是等效的还是我应该更喜欢其中一个?
可能重复:
Python:类和实例属性之间的差异
我试图用Python来理解OOP,当谈到在类中声明变量时我有点困惑.我应该在__init__
程序内部还是在程序外声明它们?有什么不同?
以下代码工作得很好:
# Declaring variables within __init__
class MyClass:
def __init__(self):
country = ""
city = ""
def information(self):
print "Hi! I'm from %s, (%s)"%(self.city,self.country)
me = MyClass()
me.country = "Spain"
me.city = "Barcelona"
me.information()
Run Code Online (Sandbox Code Playgroud)
但是声明__init__
程序之外的变量也有效:
# Declaring variables outside of __init__
class MyClass:
country = ""
city = ""
def information(self):
print "Hi! I'm from %s, (%s)"%(self.city,self.country)
me = MyClass()
me.country = "Spain"
me.city = "Barcelona"
me.information()
Run Code Online (Sandbox Code Playgroud) 我目前正在研究一个简单的基于文本的Python游戏,只是为了练习python和面向对象的编程,但我遇到了这个错误,它告诉我'LargeManaPotion'没有属性'name',当我看到它确实如此,它的声明方式与'SmallManaPotion'完全相同.我假设这是一个愚蠢的错误,我只是在俯视或者什么但是会很感激帮助.此外,当我在player.inventory函数中打印播放器的库存时,程序将打印药水,所以我不确定为什么它在交易功能中不起作用.无论如何,这是相关的代码.提前致谢.
class ManaPotion:
def __init__(self):
raise NotImplementedError("Do not create raw ManaPotion objects.")
def __str__(self):
return "{} (+{} Mana)".format(self.name, self.mana_value)
class LargeManaPotion(ManaPotion):
def __init__(self):
self.name = "Large Mana Potion"
self.mana_value = 45
self.value = 40
class SmallManaPotion(ManaPotion):
def __init__(self):
self.name = "Small Mana Potion"
self.mana_value = 15
self.value = 10
Run Code Online (Sandbox Code Playgroud)
如您所见,它与SmallManaPotion相同.这是导致错误的函数.
class TraderTile(MapTile):
def intro_text(self):
return "A frail not-quite-human, not-quite-creature squats in the corner " \
"\nclinking his gold coins together. \nHe looks willing to trade."
def __init__(self, x, y):
self.trader …
Run Code Online (Sandbox Code Playgroud) 我目前想知道为什么这个适度的代码有一个我不期望的输出:
class Product(object):
price = 0
def __init__(self, tmp_price):
self.price = tmp_price
class Market(object):
products = []
def __init__(self):
self.products.append(Product(10))
a = Market()
b = Market()
print a.products[0]
print b.products[0]
print len(a.products)
Run Code Online (Sandbox Code Playgroud)
的确,我得到了一些输出:
<__main__.Product object at 0x7fe5899e46d0>
<__main__.Product object at 0x7fe5899e46d0>
2
Run Code Online (Sandbox Code Playgroud)
有人有解释吗?我想这与python处理引用的方式有关,除了......
在使用Django一段时间之后,我习惯在没有def __init__(self): ...
声明变量的情况下使用类.我曾经在__init__
函数中声明我的变量,我现在意识到有些情况下不需要,我只是不清楚何时使用它.在尝试将类传递给变量时似乎存在问题,我应该在这些情况下使用init吗?
我知道我可以__init__
用于所有情况,但它只是使我的短课程更像没有它的清洁,所以我想知道我什么时候可以使用它.
例:
class BaseScraper(object):
# whithout __init__, passing Site() to site wont work.
# site = Site()
# parser = None
def __init__(self):
self.site = Site()
self.parser = None
class Site(object):
# no trouble declaring url as a str
url = ""
def set(self, url):
self.url = url
def get(self):
return self.url
if __name__ == "__main__":
scraper = BaseScraper()
scraper.site.set('http://www.google.com')
print scraper.site.get()
Run Code Online (Sandbox Code Playgroud) 假设我想将类方法的参数的默认值设置为类的某个数据属性的值.这样做的适当方法是什么?有没有办法使用lambda函数?
这是一些示例代码:
class A(object):
def __init__(
self
):
self._defaultReportText = "hello world"
def report(
self,
text = self._defaultReportText
):
return(text)
Run Code Online (Sandbox Code Playgroud)
显然,text
方法参数的默认值规范在report
这里不起作用,因为self
此时未定义.我该如何提供这个价值?
我有一个叫做的类run_c
,用于初始化和执行运动学模拟的运行.我将默认值分配给执行之前的属性run_c
,例如.所有这一切都是提取用户输入值,聚合到字典中,并将它们分配给相应的属性(如果它们存在).例如...x
run_c.__init__()
__init__()
run_c
import vars.Defaults as dft
class run_c:
...
dt = dft.dt
x = dft.x0
states = [ [], [], [], [] ]
...
def __init__(self, input):
for key in input.keys():
if hasattr(self, key): setattr(self, key, input[key])
...
self.execute()
Run Code Online (Sandbox Code Playgroud)
run_c.states
是一个列表,用于记录run_c
属性值随时间步长变化的列表.之后,run_c.execute()
我在内部存储x
值states[1]
,递增时间步长dt
,并x
使用速度和时间步长进行更新.这很简单,对吗?...
不过,这是问题的开始.第一次run_c
创建,初始化和执行实例时,它运行完美.但是,我通过基于从JSON文件读取的列表创建,初始化和执行多个运行来操作此模拟.因此,在驱动程序模块中......
from Run import run_c
def main():
...
for runEntry in runList:
currRun = run_c(runEntry)
...
...
Run Code Online (Sandbox Code Playgroud)
会发生的是, …
我通常声明在Python中的实例中使用的类变量的方式如下:
class MyClass(object):
def __init__(self):
self.a_member = 0
my_object = MyClass()
my_object.a_member # evaluates to 0
Run Code Online (Sandbox Code Playgroud)
但以下也有效.这是不好的做法吗?如果是这样,为什么?
class MyClass(object):
a_member = 0
my_object = MyClass()
my_object.a_member # also evaluates to 0
Run Code Online (Sandbox Code Playgroud)
第二种方法在Zope上使用,但我还没有在其他任何地方看到它.这是为什么?
编辑:作为对sr2222答案的回应.我知道这两者本质上是不同的.但是,如果该类仅用于实例化对象,则两者将以相同的方式工作.那么使用类变量作为实例变量是不是很糟糕?感觉就像是,但我无法解释原因.