Adding a variable in the global scope to a specific class - Python - python-2.7

class PhysCon:
def __init__(self):
self.tfrz = 273.15
self.cwat = 4188.0
self.cice = 2117.27
self.rhowat = 1000.0
I want to add "PhysCon().ke = 2.9". I calculated "ke" in another function that occurs after "PhysCon". How do I add "ke" to the "PhysCon" class and still have it be connected to the entire class when PhysCon() is called?

Related

Python - Overriding a parent variable with a getter/setter

So I have a parent class BaseAdd that I'm trying to subclass. The BaseAdd uses self.left and self.right, I want to use self.nodes to make it easier to access both left and right at once:
class BaseAdd():
def __init__(self, leftright):
self.left = leftright[0]
self.right = leftright[1]
class Add(BaseAdd):
def __init__(self, leftright):
self.nodes = leftright
#property
def left(self):
return self.nodes[0]
#left.setter
def left(self, value):
self.nodes[0] = value
foo = Add(('L', 'R'))
foo.left = "new"
print(foo.left, foo.nodes[0])
>>> ('new', 'L')
The problem is that the setter is never getting called, my hunch is that it's using the BaseAdd.left somehow instead. How can I make the setter properly set the list element?

Computed Property for Google Datastore

I am not sure exactly how achieve this.
I have a model defined as
class Post(ndb.Model):
author_key = ndb.KeyProperty(kind=Author)
content = ndb.StringProperty(indexed=False)
created = ndb.DateTimeProperty(auto_now_add=True)
title = ndb.StringProperty(indexed=True)
topics = ndb.StructuredProperty(Concept, repeated=True)
concise_topics = ndb.ComputedProperty(get_important_topics())
#classmethod
def get_important_topics(cls):
cls.concise_topics = filter(lambda x: x.occurrence > 2, cls.topics)
return cls.concise_topics
I like to set the value of concise_topics (Which is on the same type as topics) to a subset acheived via get_important_topics method. This should happen the moment the topics property has been set.
How do I define the "concise_topics" property in the Post class ?
With class method, you don't have access to the instance values. And also you shouldn't call the function, only pass it to the computed property, and let it call by itself.
class Post(ndb.Model):
author_key = ndb.KeyProperty(kind=Author)
content = ndb.StringProperty(indexed=False)
created = ndb.DateTimeProperty(auto_now_add=True)
title = ndb.StringProperty(indexed=True)
topics = ndb.StructuredProperty(Concept, repeated=True)
def get_important_topics(self):
return filter(lambda x: x.occurrence > 2, self.topics)
concise_topics = ndb.ComputedProperty(get_important_topics)
As far as I remember the computed property is set on each put call, so your topics should be already there by that time.

Access instance variable from instance method in python

class SimpleBond(object):
def__init__(self,OriginationDate,SettleDate,Coupon,CouponFreq,Maturity,Par,StartingPrice = None):
self.CouponCFDaysFromOrigination = np.arange(1,self.NumCouponCFs + 1) * self.CashFlowDelta
self.OriginationCashFlowDates = np.array([self.StartDate + np.timedelta64(int(i),'D') for i in self.CouponCFDaysFromOrigination])
self.StartDate = OriginationDate
def GenerateCashFlowsAndDates(self):
CashFlowDates = self.OriginationCashFlowDates
self.CashFlowDates = CashFlowDates[(CashFlowDates >= self.SettleDate) & (CashFlowDates <=self.MaturityDate)]
I have a class definition as above. Some where else I instantiate the class as below:
BondObj = SimpleBond(OriginationDate = InceptionDate,SettleDate= np.datetime64('2008-02-15'),Coupon = 8.875,CouponFreq = 2,Maturity = 9.5,Par = 100.)
BondObj.GenerateCashFlowsAndDates()
The issue is with the call to GenerateCashFlowDates() as shown above, Once the BondObj is assigned to an instantiation of the SimpleBond class with the arguments to set the state.
When I step inside the call BondObj.GenerateCashFlowsAndDates()....I can see the following state variables
self.StartDate.....its shows the actual state
where
self.OriginationCashFlowDates shows no value. It is none
As a matter of fact, all other instance variables that were set in the constructor are visible from BondObj.GenerateCashFlowAndDates() call
Many thanks

Is it dangerous to define __contains__ on a metaclass?

I'm writing a custom EnumMeta class in Python 2.7 that will collect enum keys and values from some class and augment that class with some additional fields.
class EnumMeta(type):
def __init__(cls, name, bases, props):
cls.__all_values__ = [...] # collect all interesting properties
def __contains__(cls, value):
return value in cls.__all_values__
class TheFellowshipOfTheRing(object):
__metaclass__ = EnumMeta
FRODO = 'Frodo Baggins'
SAM = 'Samwise "Sam" Gamgee'
MERRY = 'Meriadoc "Merry" Brandybuck'
PIPPIN = 'Peregrin "Pippin" Took'
GANDALF = 'Gandalf the Grey'
ARAGORN = 'Aragorn (Strider)'
LEGOLAS = 'Legolas'
GIMLI = 'Gimli'
BOROMIR = 'Boromir'
print 'Gandalf the Grey' in TheFellowshipOfTheRing
# True
print 'Saruman' in TheFellowshipOfTheRing
# False
I'm wondering if implementing container-specific functions, such as __contains__, on a metaclass is a dangerous thing to do, and if so, why?

Python Object contains list of another object throws AttributeError

Python version 3.3 w/ Aptana IDE
I'm teaching myself python in my spare time at work so I decided to recreate a poker game that my friends and I play. To facilitate the various calls to different functions I created two objects. One object contains the data for the entire game, GameData, and the second object contains a single player, Player, that I am attempting to add to GameData.
The below code loops and attempts to add Player to a list in GameData but I get an error stating:
AttributeError: type object 'GameData' has no attribute 'players'
class Player(object):
def __init__(self, seat):
self.seat = seat
self.chips = 0
self.wins = 0
self.card = 0
self.isDealer = False
class GameData(object):
def __init__(self):
self.games = 0
self.numPlayers = 0
self.chips = 0
self.players = []
self.deck = []
The below function throws the error
def testDealCards():
gd = nuts.GameData #declare GameData object
gd.deck = [7,5,5,5,3,1,5,6,1,2] #assign values to deck list
for x in range(2): #loop to create player objects in GameData
gd.players.append(Player)
gd.players[0].isDealer = True
gd.players[1].isDealer = False
print(gd.players)
nuts.dealCards(gd)
assert gd.players[0].card == 5
assert gd.players[1].card == 7
pass
You are accessing the GameData class type instead of creating an object.
Try this:
gd = nuts.GameData()