以下程序输出的是 class CLanguage: def info(self): print(self,"Python") CLanguage.info("zhang san")
时间: 2023-07-13 22:07:50 浏览: 35
这个程序会报错,因为调用类方法时需要使用类的实例,而不是类本身。正确的调用方式应该是先创建一个 CLanguage 的实例,然后再调用它的 info 方法,例如:
```
class CLanguage:
def info(self):
print(self, "Python")
language = CLanguage()
language.info() # 输出:<__main__.CLanguage object at 0x...> Python
```
相关问题
以下程序输出的是 class CLanguage: def info(self): print(" Python") clang=CLanguage() CLanguageinfo(clang)
这段程序有语法错误,应该改为以下代码才能输出结果:
```
class CLanguage:
def info(self):
print("Python")
clang = CLanguage()
clang.info()
```
输出结果为:Python
class MyRectangle: def __init__(self, width=100, height=100): self.width = width self.height = height def getArea(self): return self.width * self.height def getPerimeter(self): return 2 * (self.width + self.height) def info(self): print("矩形长为:", self.width) print("矩形宽为:", self.height) print("矩形周长为:", self.getPerimeter()) print("矩形面积为:", self.getArea())为什么这段代码在pycharm运行没有结果
这段代码没有输出结果可能是因为缺少了实例化对象和调用实例方法的代码。你可以按照以下步骤修改代码,然后再次尝试运行:
1. 在代码最后添加实例化对象的代码,例如:
```python
r1 = MyRectangle(5, 10)
```
这样就创建了一个长为 5,宽为 10 的矩形对象 r1。
2. 调用实例方法,例如:
```python
r1.info()
```
这样就可以输出矩形的长、宽、周长和面积信息了。
修改后的完整代码如下:
```python
class MyRectangle:
def __init__(self, width=100, height=100):
self.width = width
self.height = height
def getArea(self):
return self.width * self.height
def getPerimeter(self):
return 2 * (self.width + self.height)
def info(self):
print("矩形长为:", self.width)
print("矩形宽为:", self.height)
print("矩形周长为:", self.getPerimeter())
print("矩形面积为:", self.getArea())
r1 = MyRectangle(5, 10)
r1.info()
```
运行后,输出结果为:
```
矩形长为: 5
矩形宽为: 10
矩形周长为: 30
矩形面积为: 50
```
可以看到,现在已经成功输出了矩形的信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)