我试图访问不应该在__init__我的类的方法中创建的属性,但可以通过调用另一个方法来计算.我试图这样做,如果我尝试访问该属性,它不存在,它将自动计算.但是,如果属性确实存在,即使值不同,我也不希望重新计算它.例如:
class SampleObject(object):
def __init__(self, a, b):
self.a = a
self.b = b
def calculate_total(self):
self.total = self.a + self.b
sample = SampleObject(1, 2)
print sample.total # should print 3
sample.a = 2
print sample.total # should print 3
sample.calculate_total()
print sample.total # should print 4
Run Code Online (Sandbox Code Playgroud)
到目前为止,我最好的解决方案是创建一个get_total()方法来完成我需要的工作.
class SampleObject2(object):
def __init__(self, a, b):
self.a = a
self.b = b
def calculate_total(self):
self.total = self.a + self.b
def get_total(self):
if hasattr(self, 'total'):
return self.total
else:
self.calculate_total()
return self.total
sample2 …Run Code Online (Sandbox Code Playgroud) 我知道在python中使用getter和setter不是pythonic。而是应该使用属性装饰器。但我想知道以下场景 -
我有一个用几个实例属性初始化的类。然后稍后我需要向类添加其他实例属性。如果我不使用setter,那么我必须object.attribute = value在课外到处写。该类将没有self.attribute代码。当我需要跟踪类的属性时,这会不会成为问题(因为它们散布在类之外的代码中)?
我正在尝试了解Python中@property装饰器的实用程序。具体来说,我使用如下属性设置了一个类:
class A(object):
def __init__(self, x):
self._x = x
@property
def x(self):
return self._x
@x.setter
def x(self, new_x):
self._x = new_x
Run Code Online (Sandbox Code Playgroud)
而且我还建立了一个没有提供相同功能的属性的类:
class B(object):
def __init__(self, x):
self._x = x
Run Code Online (Sandbox Code Playgroud)
我创建每个实例:
a = A(10)
b = B(10)
Run Code Online (Sandbox Code Playgroud)
在iPython中运行%timeit会产生以下结果
%timeit a.x
%timeit b._x
Run Code Online (Sandbox Code Playgroud)
1000000次循环,每循环3:213 ns的最佳时间
10000000次循环,最佳3:每个循环67.9 ns
%timeit a.x = 15
%timeit b._x = 15
Run Code Online (Sandbox Code Playgroud)
1000000个循环,每个循环最好3:257 ns
10000000次循环,每循环3:89.7 ns最佳
显然,如果您要以很高的频率与该对象交谈,则@property和@setter装饰器会逊色。我的问题就是,为什么要使用它?我想听听人们可能拥有的这些装饰器的用例。谢谢。
我知道使用属性的主要目的之一是用于验证和格式化。例如,我有一个如下所示的 User 类。我希望名字和姓氏在设置时大写。如果我可以编写以下代码来实现相同的格式化结果,为什么还需要属性?
class User:
def __init__(self, firstname, lastname):
self.firstname = firstname
self.lastname = lastname
def __setattr__(self, attr, value):
if attr == 'firstname':
self.__dict__[attr] = value.capitalize()
elif attr == 'lastname':
self.__dict__[attr] = value.capitalize()
Run Code Online (Sandbox Code Playgroud) 我正在尝试自己学习Python,因此,我得到了一个用C#编写的软件,并试图用Python重新编写它.鉴于以下课程,我有几个问题:
C#
sealed class Message
{
private int messageID;
private string message;
private ConcurrentBag <Employee> messageFor;
private Person messageFrom;
private string calltype;
private string time;
public Message(int iden,string message, Person messageFrom, string calltype,string time)
{
this.MessageIdentification = iden;
this.messageFor = new ConcurrentBag<Employee>();
this.Note = message;
this.MessageFrom = messageFrom;
this.CallType = calltype;
this.MessageTime = time;
}
public ICollection<Employee> ReturnMessageFor
{
get
{
return messageFor.ToArray();
}
}
Run Code Online (Sandbox Code Playgroud)
在我的类中,我有一个名为messageFor的线程安全集合,在Python中是否存在等价物?如果是这样,我如何在python类中实现它?
我的线程安全集合也有一个吸气剂?我如何在Python中做同样的事情?
Python有一个EqualsTo方法来测试对象之间的相等性吗?或者相当于Python中的这个?
public override bool Equals(object obj)
{
if (obj == null)
{
return …Run Code Online (Sandbox Code Playgroud)我想在模型上设置非持久属性。我尝试了以下方法:
class class User(models.Model):
email = models.EmailField(max_length=254, unique=True, db_index=True)
@property
def client_id(self):
return self.client_id
Run Code Online (Sandbox Code Playgroud)
然后:
user = User.objects.create(email='123', client_id=123)
print(user.client_id)
Run Code Online (Sandbox Code Playgroud)
我收到错误:无法设置attribute。为什么?
无法从有关此主题的其他线程中得到直接答案:
在 Python 中,使用之间的主要区别是什么
class Foo(object):
def __init__(self, x):
self.x = x
Run Code Online (Sandbox Code Playgroud)
和
class Foo(object):
def __init__(self, x):
self._x = x
@property
def x(self):
return self._x
Run Code Online (Sandbox Code Playgroud)
从外观上看,以这种方式使用@property 会使 x 只读……但也许有人有更好的答案?谢谢/弗雷德
我越来越深入地了解 python,发现很难理解接口的概念。
\n\n这个问题更具理论性。
\n\n据我了解,为最终用户(非开发人员用户)提供一个接口是可取的,但是为什么类也应该具有供其他对象/类(基本上是其他程序/程序员)使用的接口?\n在示例中,在 B 类中使用 comment1 或 comment 2 如何改变程序的功能?
\n\nclass A():\n def __init__(self,a):\n self.a = a\n print self.a\n def seta(self,newa): #setter\n self.a = newa\n print self.a\n def geta(self): #getter\n return self.a\n\n\nclass B(object):\n def __init__(self,oobj,b):\n self.b = b\n self.oobj = oobj\n print self.b\n def addab(self):\n #a = self.oobj.geta() # \xe2\x80\x94> 1. using interface : the getter method \n #return (self.b +a)\n return (self.b+self.oobj.a) # \xe2\x80\x94> 2.directly accessing the a attribute\nRun Code Online (Sandbox Code Playgroud)\n\n希望我已经说清楚了..
\n\n编辑:\n我确实检查了提到的可能重复的其他线程,但即使在尝试理解@property之前,我也试图理解不通过程序内的不同对象自行修改属性背后的基本原理。
\n当我在Python中创建一个类时,我必须使用以下内容声明变量self.:
class ClassName(object):
def __init__(self, arg):
super(ClassName, self).__init__()
self.arg = arg
Run Code Online (Sandbox Code Playgroud)
很好,但要实例化它,我需要将参数传递给init方法......但如果我没有它们,或者不想打扰它们怎么办?
我想要类似的东西
def __init__(self):
super(ClassName, self).__init__()
self.arg
Run Code Online (Sandbox Code Playgroud)
......以后再提到现有但空洞的arg.编辑.通过现有但空的我意味着类似C的行为:
int a;
Run Code Online (Sandbox Code Playgroud)
......变量a存在但没有价值.即使是gcc也认为它是空的,所以我认为这个问题很清楚.
默认值尽可能接近我想要的,我将使用它.
我正在使用Python中的图形库,我正在以这种方式定义我的vetex:
class Vertex:
def __init__(self,key,value):
self._key = key
self._value = value
@property
def key(self):
return self._key
@key.setter
def key(self,newKey):
self._key = newKey
@property
def value(self):
return self._value
@value.setter
def value(self,newValue):
self.value = newValue
def _testConsistency(self,other):
if type(self) != type(other):
raise Exception("Need two vertexes here!")
def __lt__(self,other):
_testConsistency(other)
if self.index <= other.index:
return True
return False
......
Run Code Online (Sandbox Code Playgroud)
我真的必须自己定义__lt __,__ eq __,__ ne __.它太冗长了.有更简单的方法可以解决这个问题吗?干杯.请不要使用__cmp__,因为它将在python 3中消失.
我正在实现从Java到Python的移植.现在,我想通过使用另一个对象作为嵌套属性来定义对象.
需要明确的是,考虑到Java代码如下:
public class Foo {
private String fooName;
public Foo(String fooName) {
setFooName(fooName);
}
public void setFooName(String fooName) {
this.fooName = fooName;
}
public String getFooName() {
return this.fooName;
}
}
public class Bar {
private String barName;
private Foo foo;
public Bar(String barName, Foo foo) {
setBoName(fooName);
setFoo(foo);
}
public void setBarName(String barName) {
this.barName = barName;
}
public String getBarName() {
return this.barName;
}
public void setFoo(Foo foo) {
this.foo = foo;
}
public Foo getFoo() { …Run Code Online (Sandbox Code Playgroud) 我编写了一个模拟abc模块和模块使用的代码properties.但是,似乎我无法访问width和height变量.代码如下:
from abc import ABCMeta, abstractmethod
class Polygon:
__metaclass__ = ABCMeta
@abstractmethod
def compute_area(self): pass
def __init__(self):
self.width = None
self.height = None
@property
def width_prop(self):
return self.width
@property
def height_prop(self):
return self.height
@width_setter.setter
def width_setter(self, width):
self.width = width
@height_setter.setter
def height_setter(self, height):
self.height = height
class Triangle(Polygon):
def compute_area(self):
return 0.5 * width * height
if __name__ == "__main__":
tri = Triangle()
tri.height_setter(20)
tri.width_setter(30)
print "Area of the triangle = …Run Code Online (Sandbox Code Playgroud) df.shape #we check the shape of dataset
(1338, 7)
Run Code Online (Sandbox Code Playgroud)
在调用上述形状函数时,我们没有使用 (),但对于大多数其他函数,我们使用 ()。这是为什么?
df.info()# gives the info of the dataset
Run Code Online (Sandbox Code Playgroud) python ×13
properties ×4
python-3.x ×3
oop ×2
abc ×1
c# ×1
function ×1
java ×1
performance ×1
self ×1