简体   繁体   English

python 2.7实例化另一个类中的类

[英]python 2.7 Instantiating class in another class

I am writing a class, Tbeam (Python 2.7.8 in IPython notebook 2.2.0) that calculates values for a reinforced concrete T beam. 我正在编写一个类,Tbeam(IPython笔记本2.2.0中的Python 2.7.8)来计算钢筋混凝土T梁的值。 The flange and web of the Tbeam are considered to be objects of the class Rectangle. Tbeam的法兰和腹板被认为是Rectangle类的对象。 I instantiate a flange and web from the class Rectangle in the class Tbeam, and create methods to calculate the overall depth (d) and area (area) of the Tbeam. 我从Tbeam类的Rectangle类实例化了一个法兰和腹板,并创建了一些方法来计算Tbeam的整体深度(d)和面积(面积)。

class Rectangle:
"""A class to create simple rectangle with dimensions width (b) and 
height (d). """

def __init__(self, b, d ):
    """Return a rectangle object whose name is *name* and default
    dimensions are width = 1, height = 1.
    """
    self.width = b
    self.height = d

def area(self):
    """Computes the area of a rectangle"""
    return self.width * self.height

def inertia(self):
    """Computes the moment of inertia of a rectangle,
    with respect to the centroid."""

    return self.width*math.pow(self.height,3)/12.0

def perim(self):
    """Calculates the perimeter of a rectangle"""
    return 2*(self.width+self.height)

def centroid(self):
    """Calculates the centroid of a rectangle"""
    return self.height/2.0

def d(self):
    """Returns the height of the rectangle."""
    return self.height

def bf(self):
    """Returns the width of the rectangle."""
    return self.width

- --

class Tbeam:

"""A class to create T beams with dimensions:
bf = width of top flange,
tf = thickness of top flange,
d = height of web,
bw = width of web. """

def __init__(self, bf,tf,d,bw):
    self.bf = bf
    self.tf = tf
    self.d = d
    self.bw = bw
    self.flange = Rectangle(bf,tf)
    self.web = Rectangle(bw,d)

def area(self):
    area =self.flange.area + self.web.area

def d(self):
    """Returns the total height of the Tbeam"""
    return self.flange.d + self.web.d

- --

When I execute the test cell 当我执行测试单元时

# Test Tbeam
t1 = Tbeam(60.0, 5.0,27.0,12.0)
print t1.d
print t1.area

- --

I get the following: 我得到以下内容:

27.0

bound method Tbeam.area of <__main__.Tbeam instance at 0x7f8888478758

27.0 is correct but I do not understand the second response for print t1.area. 27.0是正确的,但我不了解打印t1.area的第二个响应。 I assume my definition for area is incorrect but I don't know how to correct the problem. 我认为我对区域的定义不正确,但是我不知道如何解决该问题。

Many thanks 非常感谢

Ron 罗恩

You're printing t1.area which is a method. 您正在打印t1.area ,这是一种方法。 You want to print the result of calling the method, so print t1.area() . 您要打印调用方法的结果,因此请print t1.area()

area method is defined as 面积法定义为

def area(self):
    area =self.flange.area + self.web.area

but should be defined as 但应定义为

def area(self):
    area =self.flange.area() + self.web.area()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM