Python – best way to have interdependent variable in a class

Newbie Python questions: I want to model something that can have a several inter-connected instance variables and if I set one, I want to recalculate the others. Any can be set.

E.g. a circle – each instance has an area, circumference and radius (let’s ignore the diameter). If I set the area, I want the circumference & radius re-calculated and vice-versa. Should I :

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>class circle:
def area(self):
return cmath.pi*self.radius*self.radius
def circumference(self):
return 2 * cmath.pi * self.radius
def radius(self):
return self.circumference/(2*cmath.pi)
circle1 = circle()
circle1.radius = 5
print "Circle1's area is {0} and its circumference is {1}".format(circle1.area, circle1.circumference)
</code>
<code>class circle: def area(self): return cmath.pi*self.radius*self.radius def circumference(self): return 2 * cmath.pi * self.radius def radius(self): return self.circumference/(2*cmath.pi) circle1 = circle() circle1.radius = 5 print "Circle1's area is {0} and its circumference is {1}".format(circle1.area, circle1.circumference) </code>
class circle:

   def area(self):
       return cmath.pi*self.radius*self.radius

   def circumference(self):
      return 2 * cmath.pi * self.radius

   def radius(self):
      return self.circumference/(2*cmath.pi)

circle1 = circle()
circle1.radius = 5
print "Circle1's area is {0} and its circumference is {1}".format(circle1.area, circle1.circumference) 

Now there’s nothing in the code sample to calculate the area once the radius has been set, so do I need @property with setters and getters for the radius, area and circumference to calculate the other attributes when this one is set or am I barking up completely the wrong tree?

Instead of keeping 3 member fields and synchronizing them, you only need to store one actual value in memory – the radius is a good choice in this example – and always use it:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import cmath
class Circle(object):
def __init__(self, radius=0.0):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, radius):
self._radius = float(radius)
@property
def area(self):
return cmath.pi * self._radius * self._radius
@area.setter
def area(self, area):
self._radius = (area / cmath.pi) ** 0.5
@property
def circumference(self):
return 2 * cmath.pi * self._radius
@circumference.setter
def circumference(self, circumference):
self._radius = circumference / cmath.pi / 2
circle1 = Circle()
circle1.radius = 5
print "Circle1's radius is {0}, it's area is {1} and it's circumference is {2}".format(circle1.radius, circle1.area, circle1.circumference)
circle1.area = 5
print "Circle1's radius is {0}, it's area is {1} and it's circumference is {2}".format(circle1.radius, circle1.area, circle1.circumference)
circle1.circumference = 5
print "Circle1's radius is {0}, it's area is {1} and it's circumference is {2}".format(circle1.radius, circle1.area, circle1.circumference)
</code>
<code>import cmath class Circle(object): def __init__(self, radius=0.0): self._radius = radius @property def radius(self): return self._radius @radius.setter def radius(self, radius): self._radius = float(radius) @property def area(self): return cmath.pi * self._radius * self._radius @area.setter def area(self, area): self._radius = (area / cmath.pi) ** 0.5 @property def circumference(self): return 2 * cmath.pi * self._radius @circumference.setter def circumference(self, circumference): self._radius = circumference / cmath.pi / 2 circle1 = Circle() circle1.radius = 5 print "Circle1's radius is {0}, it's area is {1} and it's circumference is {2}".format(circle1.radius, circle1.area, circle1.circumference) circle1.area = 5 print "Circle1's radius is {0}, it's area is {1} and it's circumference is {2}".format(circle1.radius, circle1.area, circle1.circumference) circle1.circumference = 5 print "Circle1's radius is {0}, it's area is {1} and it's circumference is {2}".format(circle1.radius, circle1.area, circle1.circumference) </code>
import cmath

class Circle(object):
    def __init__(self, radius=0.0):
        self._radius = radius

    @property
    def radius(self):
       return self._radius

    @radius.setter
    def radius(self, radius):
        self._radius = float(radius)

    @property
    def area(self):
       return cmath.pi * self._radius * self._radius

    @area.setter
    def area(self, area):
        self._radius = (area / cmath.pi) ** 0.5

    @property
    def circumference(self):
        return 2 * cmath.pi * self._radius

    @circumference.setter
    def circumference(self, circumference):
        self._radius = circumference / cmath.pi / 2

circle1 = Circle()
circle1.radius = 5
print "Circle1's radius is {0}, it's area is {1} and it's circumference is {2}".format(circle1.radius, circle1.area, circle1.circumference)

circle1.area = 5
print "Circle1's radius is {0}, it's area is {1} and it's circumference is {2}".format(circle1.radius, circle1.area, circle1.circumference)

circle1.circumference = 5
print "Circle1's radius is {0}, it's area is {1} and it's circumference is {2}".format(circle1.radius, circle1.area, circle1.circumference)

This solution seems too obvious though – is there a specific reason you want to have separate member fields? You can usually find a smaller number of values you can calculate the rest from…

7

A fool-proof and robust way of dealing with dependent attributes is to use my small pure-python module exactly for handling acyclic dependencies in python class attributes, also known as dataflow programming.

Sometimes it is not feasible to simply update all attributes when one is changed. Ideally, changing an attribute doesn’t cause any updates. Only getting an attribute should cause updates, and only the required updates.

That is exactly what the module does. It is very easy to implement in any class definition.

For instance, consider an attribute dependency structure shown below:

enter image description here

This dependency structure is completely defined using the library’s descriptors:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> class DataflowSuccess():
# The following defines the directed acyclic computation graph for these attributes.
a1 = IndependentAttr(init_value = 1, name = 'a1')
a2 = DeterminantAttr(dependencies = ['a1'], calc_func = 'update_a2', name = 'a2')
a3 = DeterminantAttr(dependencies = ['a2'], calc_func = 'update_a3', name = 'a3')
a4 = DeterminantAttr(dependencies = ['a1','a2'], calc_func = 'update_a4', name = 'a4')
a5 = DeterminantAttr(dependencies = ['a1','a2','a3','a6'], calc_func = 'update_a5', name = 'a5')
a6 = IndependentAttr(init_value = 6, name = 'a6')
a7 = DeterminantAttr(dependencies = ['a4','a5'], calc_func = 'update_a7', name = 'a7')
# ...... define the update functions update_a2, update_a3 etc
def update_a2():
....
</code>
<code> class DataflowSuccess(): # The following defines the directed acyclic computation graph for these attributes. a1 = IndependentAttr(init_value = 1, name = 'a1') a2 = DeterminantAttr(dependencies = ['a1'], calc_func = 'update_a2', name = 'a2') a3 = DeterminantAttr(dependencies = ['a2'], calc_func = 'update_a3', name = 'a3') a4 = DeterminantAttr(dependencies = ['a1','a2'], calc_func = 'update_a4', name = 'a4') a5 = DeterminantAttr(dependencies = ['a1','a2','a3','a6'], calc_func = 'update_a5', name = 'a5') a6 = IndependentAttr(init_value = 6, name = 'a6') a7 = DeterminantAttr(dependencies = ['a4','a5'], calc_func = 'update_a7', name = 'a7') # ...... define the update functions update_a2, update_a3 etc def update_a2(): .... </code>
 class DataflowSuccess():

    # The following defines the directed acyclic computation graph for these attributes.
    a1 = IndependentAttr(init_value = 1, name = 'a1')
    a2 = DeterminantAttr(dependencies = ['a1'], calc_func = 'update_a2', name = 'a2')
    a3 = DeterminantAttr(dependencies = ['a2'], calc_func = 'update_a3', name = 'a3')
    a4 = DeterminantAttr(dependencies = ['a1','a2'], calc_func = 'update_a4', name = 'a4')
    a5 = DeterminantAttr(dependencies = ['a1','a2','a3','a6'], calc_func = 'update_a5', name = 'a5')
    a6 = IndependentAttr(init_value = 6, name = 'a6')
    a7 = DeterminantAttr(dependencies = ['a4','a5'], calc_func = 'update_a7', name = 'a7')


    # ...... define the update functions update_a2, update_a3 etc
    def update_a2():
        ....

The module takes care of the rest. Changing an attribute causes its children (attributes it affects) (and their children, etc) to know their values need to be recalculated in the future. When the value of an attribute is requested by calling __get__ (for instance by executing obj.a5), only the required updates occur, all automatically behind the scenes.

If it doesn’t suit your needs, at least it is a helpful example of how the descriptor functionalities work. This example is available at the github page. Descriptors provide lots of flexibility for modifying how __get__ and __set__ and __del__ work for your class attributes, which can solve dependency problems.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật